package com.zuipin.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.zuipin.entity.BalanceRecord;
import com.zuipin.entity.IntegralRecord;
import com.zuipin.entity.Member;
import com.zuipin.entity.MemberAccount;
import com.zuipin.entity.OrderConsignee;
import com.zuipin.entity.OrderDetail;
import com.zuipin.entity.OrderInfo;
import com.zuipin.entity.OrderInfoLog;
import com.zuipin.entity.OrderInvoiceInfo;
import com.zuipin.entity.PayOrder;
import com.zuipin.entity.RedPacket;
import com.zuipin.entity.RocketMqInfo;
import com.zuipin.entity.RuleSetUseLog;
import com.zuipin.entity.SysUser;
import com.zuipin.entity.ThirdAccount;
import com.zuipin.entity.product.CategoryInfo;
import com.zuipin.entity.product.ProductInfo;
import com.zuipin.entity.shoppingCart.CartParam;
import com.zuipin.entity.shoppingCart.Gift;
import com.zuipin.entity.shoppingCart.ShoppingCart;
import com.zuipin.entity.shoppingCart.ShowType;
import com.zuipin.enums.BalanceType;
import com.zuipin.enums.GrowthValType;
import com.zuipin.enums.IntegralType;
import com.zuipin.enums.InvoiceType;
import com.zuipin.enums.OrderStatusEnum;
import com.zuipin.enums.PayType;
import com.zuipin.enums.PremiumEnum;
import com.zuipin.enums.RedPackStatus;
import com.zuipin.enums.RocketMQTagEnum;
import com.zuipin.enums.TimeDotType;
import com.zuipin.framework.emuns.ErrorCode;
import com.zuipin.framework.exception.CustomException;
import com.zuipin.framework.result.Result;
import com.zuipin.mapper.OrderConsigneeMapper;
import com.zuipin.mapper.OrderDetailMapper;
import com.zuipin.mapper.OrderInfoLogMapper;
import com.zuipin.mapper.OrderInfoMapper;
import com.zuipin.mapper.OrderInvoiceInfoMapper;
import com.zuipin.mapper.PayOrderMapper;
import com.zuipin.mapper.RuleSetUseLogMapper;
import com.zuipin.service.IBalanceRecordService;
import com.zuipin.service.ICategoryInfoService;
import com.zuipin.service.IDeliveryAddressService;
import com.zuipin.service.IGiftGivingService;
import com.zuipin.service.IIntegralRecordService;
import com.zuipin.service.IMemberAccountService;
import com.zuipin.service.IMemberService;
import com.zuipin.service.IOrderService;
import com.zuipin.service.IPayOrderService;
import com.zuipin.service.IProductInfoService;
import com.zuipin.service.IRedPacketService;
import com.zuipin.service.IRocketMQService;
import com.zuipin.service.IRuleSetService;
import com.zuipin.service.IShoppingCartService;
import com.zuipin.service.ISysUserService;
import com.zuipin.service.IThirdAccountService;
import com.zuipin.util.ArithUtil;
import com.zuipin.util.CommonUtils;
import com.zuipin.util.ConstantsUtil;
import com.zuipin.util.Convert;
import com.zuipin.util.DateUtils;
import com.zuipin.util.HttpUtil;
import com.zuipin.util.Pagination;
import com.zuipin.util.StringUtil;
import com.zuipin.vo.BackOrderResultVo;
import com.zuipin.vo.BackOrderVo;
import com.zuipin.vo.CalculateInfoVo;
import com.zuipin.vo.CalculateResultVo;
import com.zuipin.vo.CloseOrderPrompt;
import com.zuipin.vo.CommentProductVo;
import com.zuipin.vo.OrderConsigneeVo;
import com.zuipin.vo.OrderInfoVo;
import com.zuipin.vo.OrderSerachVo;
import com.zuipin.vo.ProExtInfoVo;
import com.zuipin.vo.ProExtSerachVo;
import com.zuipin.vo.ProductAmountVo;
import com.zuipin.vo.ProductExtVo;
import com.zuipin.vo.RedPacketVo;
import com.zuipin.vo.RuleSetUserLogVo;
import com.zuipin.vo.UseRuleSetVo;

import net.sf.json.JSONNull;

@Service
public class OrderServiceImpl implements IOrderService {
	@Resource
	private OrderInfoMapper			orderInfoMap;
	@Resource
	private OrderConsigneeMapper	orderConsigneeMapper;
	protected final Logger			log	= Logger.getLogger(getClass());
	@Resource
	private OrderInfoLogMapper		orderInfoLogMapper;
	@Resource
	private OrderDetailMapper		orderDetailMapper;
	@Resource
	private ISysUserService			sysUserService;
	@Resource
	private IMemberService			memberService;
	@Resource
	private OrderInvoiceInfoMapper	orderInvoiceInfoMapper;
	
	@Resource
	private IPayOrderService		payOrderService;
	@Resource
	private PayOrderMapper			payOrderMapper;
	@Resource
	private IRedPacketService		redPacketService;
	@Resource
	private IIntegralRecordService	integralRecordService;
	@Resource
	private IProductInfoService		productInfoService;
	
	@Resource
	private IThirdAccountService	thirdAccountService;
	@Resource
	private IRocketMQService		rocketMQService;
	@Resource
	private IBalanceRecordService	balanceRecordService;
	
	@Resource
	private IDeliveryAddressService	deliveryAddressService;
	
	@Resource
	private IShoppingCartService	shoppingCartService;
	
	@Resource
	private RuleSetUseLogMapper		ruleSetUseLogMapper;
	
	@Resource
	private IMemberAccountService	memberAccountService;
	
	@Resource
	private IGiftGivingService		giftGivingService;
	
	@Resource
	private IRuleSetService			ruleSetService;
	
	@Value("${oms.confimReceiptUrl}")
	private String					confimReceiptUrl;
	@Value("${wms.finsSubOrderUrl}")
	private String					finsSubOrderUrl;
	@Value("${oms.closeOrderUrl}")
	private String					closeOrderUrl;
	
	@Value("${oms.sendOrderInfoToOms}")
	private String					sendOrderInfoToOms;
	@Resource
	private ICategoryInfoService	categoryInfoService;
	
	/**
	 * @Description:修改订单状态（处理中变为配送中/打包中）（将订单状态从配送中/打包中变为已发货)
	 * @Title:
	 * @author: xujinding
	 * @date: 2017年3月29日下午2:24:54
	 */
	@Override
	public Result updateOrderToPackOrDelivered(String orderNo, String status, Long sysUserId, String ip, Result res) {
		OrderInfo orderInfo = orderInfoMap.findOrderInfoByOrderNo(orderNo);
		if (orderInfo != null) {
			if (OrderStatusEnum.已发货.getValue().equals(status)) {
				if (OrderStatusEnum.打包中.getValue().equals(orderInfo.getOrderStatus())) {
					updateOrderStatus(orderNo, OrderStatusEnum.已发货.getIndex(), sysUserId, null, "将订单状态从配送中/打包中变为已发货", ip, null);
					res.setErrorCode(ErrorCode.SUCCESS);
				} else {
					res.setErrorCode(ErrorCode.ORDER_ERRPR);
					res.setMessage("只有打包中待发货才能变成已发货");
				}
			} else if (OrderStatusEnum.打包中.getValue().equals(status)) {
				if (OrderStatusEnum.处理中.getValue().equals(orderInfo.getOrderStatus())) {
					updateOrderStatus(orderNo, OrderStatusEnum.打包中.getIndex(), sysUserId, null, "将订单状态从处理中变为配送中/打包中", ip, null);
					res.setErrorCode(ErrorCode.SUCCESS);
				} else {
					res.setErrorCode(ErrorCode.ORDER_ERRPR);
					res.setMessage("只有处理中的状态才能变成打包中待发货");
				}
			} else if (OrderStatusEnum.处理中.getValue().equals(status)) {
				if (OrderStatusEnum.待审核.getValue().equals(orderInfo.getOrderStatus()) || OrderStatusEnum.支付成功待审核.getValue().equals(orderInfo.getOrderStatus())
						|| OrderStatusEnum.打包中.getValue().equals(orderInfo.getOrderStatus())) {
					updateOrderStatus(orderNo, OrderStatusEnum.处理中.getIndex(), sysUserId, null, "将订单状态从处理中变为配送中/打包中", ip, null);
					res.setErrorCode(ErrorCode.SUCCESS);
				} else {
					res.setErrorCode(ErrorCode.ORDER_ERRPR);
					res.setMessage("只有待审核或打包中或支付成功待审核的状态才能变成处理中");
				}
				
			} else {
				res.setErrorCode(ErrorCode.ORDER_ERRPR);
				res.setMessage("订单类型错误");
			}
		} else {
			res.setErrorCode(ErrorCode.ORDER_ERRPR);
			res.setMessage("查无订单");
		}
		return res;
	}
	
	/**
	 * @Description:修改订单状态
	 * @Title:
	 * @author: xujinding
	 * @date: 2017年3月29日下午2:24:54
	 */
	public void updateOrderStatus(String orderNo, Integer status, Long sysUserId, Long memberId, String updateInfo, String ip, String remark) {
		OrderInfo orderInfo = orderInfoMap.findOrderInfoByOrderNo(orderNo);
		if (orderInfo != null) {
			String oldStatus = orderInfo.getOrderStatus();
			orderInfo.setOrderStatus(OrderStatusEnum.getValueByIndex(status));
			orderInfo.setUpdateId(sysUserId);
			orderInfo.setUpdateTime(DateUtils.getCurrentDateTime());
			if (OrderStatusEnum.处理中.getValue().equals(OrderStatusEnum.getValueByIndex(status))) {
				// 要变成处理中以后两种情况
				// 1：审核通过（此时打包时间为空，要设置审核人，和时间）
				// 2:取消拆单（此时打包时间不空，不用设置审核人和时间）
				if (StringUtil.isBlank(orderInfo.getPackTime())) {
					orderInfo.setOrderAuditId(sysUserId);
					orderInfo.setOrderAuditTime(DateUtils.getCurrentDateTime());
				}
				orderInfo.setPackTime(null);
			} else if (OrderStatusEnum.打包中.getValue().equals(OrderStatusEnum.getValueByIndex(status))) {
				orderInfo.setPackTime(DateUtils.getCurrentDateTime());
			} else if (OrderStatusEnum.已发货.getValue().equals(OrderStatusEnum.getValueByIndex(status))) {
				orderInfo.setSendTime(DateUtils.getCurrentDateTime());
			} else if (OrderStatusEnum.已取消.getValue().equals(OrderStatusEnum.getValueByIndex(status))) {
				
				orderInfo.setCancelTime(DateUtils.getCurrentDateTime());
				// 客服做取消操作--需求要求
				if (sysUserId != null) {
					orderInfo.setOrderAuditId(sysUserId);
					orderInfo.setOrderAuditTime(DateUtils.getCurrentDateTime());
					// 订单器
					if (SysUser.QUARTZ.equals(sysUserId)) {
						orderInfo.setCancelReason("取消订单——" + remark);
					} else {
						orderInfo.setCancelReason("拒绝订单——" + remark);
					}
				} else {
					orderInfo.setCancelReason("取消订单——" + remark);
				}
				
				PayOrder payOrder = payOrderMapper.selectByPrimaryKey(orderInfo.getPaymentOrderId());
				payOrder.setCancelTime(DateUtils.getCurrentDateTime());
				payOrder.setUpdateId(sysUserId);
				payOrder.setUpdateTime(DateUtils.getCurrentDateTime());
				payOrder.setCancelTime(DateUtils.getCurrentDateTime());
				payOrderMapper.updateByPrimaryKeySelective(payOrder);
			} else if (OrderStatusEnum.已关闭.getValue().equals(OrderStatusEnum.getValueByIndex(status))) {
				orderInfo.setCloseReason("关闭订单——" + remark);
				orderInfo.setOrderCloseTime(DateUtils.getCurrentDateTime());
				orderInfo.setOrderAuditId(sysUserId);
				orderInfo.setOrderAuditTime(DateUtils.getCurrentDateTime());
				orderInfo.setOrderCloseId(sysUserId);
				orderInfo.setIsGiveGrowthValue(OrderInfo.IS_GIVE_GROWTH_VALUE_NO_0);
			} else if (OrderStatusEnum.订单完成.getValue().equals(OrderStatusEnum.getValueByIndex(status))) {
				// 用户确认收货
				String receiptName = ConstantsUtil.RECEIPT_NAME_MEMBER;
				if (sysUserId != null) {
					// 系统确认收货
					receiptName = ConstantsUtil.RECEIPT_NAME_SYSTEM;
				}
				orderInfo.setReceiptName(receiptName);
				orderInfo.setIsGiveGrowthValue(OrderInfo.IS_GIVE_GROWTH_VALUE_YES_1);
				orderInfo.setReceiptTime(DateUtils.getCurrentDateTime());
			}
			
			orderInfoMap.updateByPrimaryKeySelective(orderInfo);
			OrderInfoLog orderInfoLog = new OrderInfoLog();
			orderInfoLog.setCreateTime(DateUtils.getCurrentDateTime());
			orderInfoLog.setIpAddress(ip);
			// orderInfoLog.setDelFlag(BaseEntity.DEL_FLAG_YES);
			orderInfoLog.setSysUserId(sysUserId);
			orderInfoLog.setMemberId(memberId);
			orderInfoLog.setUpdateInfo(updateInfo);
			orderInfoLog.setOrderNo(orderInfo.getOrderNo());
			orderInfoLog.setAfterStatus(OrderStatusEnum.getValueByIndex(status));
			orderInfoLog.setBeforeStatus(oldStatus);
			// orderInfoLog.setUpdateSrc((memberOrSystem.shortValue()));
			orderInfoLogMapper.insertSelective(orderInfoLog);
		}
	}
	
	/**
	 * 取消订单
	 * @throws Exception 
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Result cancelOrder(Long payId, Long sysUserId, Long memberId, String ip, Result result, String cancelReason) throws CustomException {
		// 未支付,并且不是货到付款才能取消付款单
		PayOrder payOrder = payOrderMapper.selectByPrimaryKey(payId);
		if (payOrder != null) {
			if ((PayOrder.YES.equals(payOrder.getPayStatus()))) {
				result.setErrorCode(ErrorCode.ORDER_ERRPR);
				result.setMessage("已支付不能取消");
				return result;
			}
			List<OrderInfo> listOrder = orderInfoMap.findOrderListByPayId(payId);
			if (listOrder == null || listOrder.size() < 1) {
				
				result.setErrorCode(ErrorCode.ORDER_ERRPR);
				result.setMessage("查无订单");
				return result;
			}
			OrderInfo oi = listOrder.get(0);
			
			if (OrderStatusEnum.待审核.getValue().equals(oi.getOrderStatus()) || OrderStatusEnum.待付款.getValue().equals(oi.getOrderStatus())) {
				if ((PayType.CASH_DELIVERY + "").equals(payOrder.getPayType())) {
					if (!OrderStatusEnum.待审核.getValue().equals(oi.getOrderStatus())) {
						
						result.setErrorCode(ErrorCode.ORDER_ERRPR);
						result.setMessage("货到付款待审核才能取消");
						return result;
					}
				}
				if (sysUserId == null) {
					memberId = payOrder.getCreateMemberId();
				} else {
					memberId = null;
					
				}
				
				updateOrderStatus(oi.getOrderNo(), OrderStatusEnum.已取消.getIndex(), sysUserId, memberId, "操作取消订单", ip, cancelReason);
				RedPacket redPacket = new RedPacket();
				redPacket.setId(payOrder.getUseRedPacketId());
				redPacket.setStatus(com.zuipin.enums.RedPackStatus.UNUSED);
				redPacketService.update(redPacket);
				
				// 将用户使用的充值积分返回
				balanceRecordService.updateBalance(payOrder.getCreateMemberId(), payOrder.getSysId(), sysUserId == null ? payOrder.getCreateMemberId() : sysUserId,
						sysUserId == null ? payOrder.getCreateMemberId() : sysUserId, payOrder.getUseStoreValue(), com.zuipin.enums.BalanceType.CANCEL_BACK, "账户余额退回", "订单号",
						oi.getOrderNo(), BalanceRecord.IS_BUY_NO);
				
				integralRecordService.addIntegralRecord(payOrder.getCreateMemberId(), payOrder.getSysId(), sysUserId, sysUserId, payOrder.getUseJfSum(),
						com.zuipin.enums.IntegralType.CANCEL_BACK, "积分退回", "订单号", oi.getOrderNo(), IntegralRecord.IS_BUY_NO);
				
				// 积分和充值回收
				this.doRecoveryJfAndStore(oi, payOrder, sysUserId, BalanceType.ORDER_RECYCLING, IntegralType.ORDER_RECYCLING, 0);
				
				List<OrderDetail> orderDetails = orderDetailMapper.findOrderDetailListByOrderId(oi.getId());
				
				String worker = "";
				if (memberId != null) {
					Member member = memberService.findById(memberId);
					if (member == null) {
						throw new CustomException(ErrorCode.ORDER_ERRPR.getCode(), "查询不到下单人员");
					}
					worker = member.getContactName() + "";
				} else {
					SysUser sysUser = sysUserService.findById(sysUserId);
					if (sysUser == null) {
						throw new CustomException(ErrorCode.ORDER_ERRPR.getCode(), "查询不到操作人员");
					}
					worker = sysUser.getRealName() + "";
				}
				
				boolean isHoldSuccess = payOrderService.preholdCisStock(orderDetails, PayOrder.PRE_RELEASE_STOCK, oi, "取消订单释放虚拟预占", worker, payOrder.YES);
				if (!isHoldSuccess) {
					throw new CustomException(ErrorCode.ORDER_ERRPR.getCode(), "取消订单释放虚拟预占失败,请检查cis有无该商品，或其他原因");
				}
				result.setErrorCode(ErrorCode.SUCCESS);
				return result;
			} else {
				result.setErrorCode(ErrorCode.ORDER_ERRPR);
				result.setMessage("该状态下不能取消订单");
				return result;
			}
			
		} else {
			result.setErrorCode(ErrorCode.ORDER_ERRPR);
			result.setMessage("查无付款单");
			return result;
		}
		
	}
	
	/**
	 * @throws CustomException 
	 * 
	 * @Title: doJfAndStore 
	 * @Description: 回收积分和充值
	 * @author xujinding
	 * @param @param orderId 
	 * @param giveJfSum  确认收货  也有送积分回收
	 * 
	 * @return void
	 * @throws
	 */
	public void doRecoveryJfAndStore(OrderInfo oi, PayOrder payOrder, Long sysUserId, BalanceType balanceType, IntegralType integralType, int giveJfSum) throws CustomException {
		// 将送用户的回收
		List<RuleSetUseLog> logList = ruleSetUseLogMapper.findIntegralAndBalance(oi.getId());
		int jfSum = 0 + giveJfSum;
		BigDecimal storeValue = new BigDecimal(0.00);
		List<Long> ruleSetUseLogId = new ArrayList<>();// 要回收的日志Id
		// 累加 要回收的积分和充值
		if (logList != null && !logList.isEmpty()) {
			for (RuleSetUseLog ruleLog : logList) {
				// List<String> ruleIds = StringUtil.splitString(ruleLog.getGiveRuleSetIds());
				if (ShowType.GIVE_INTEGRAL.toString().equals(ruleLog.getShowType())) {
					// jfSum = jfSum + (ruleLog.getGiveNum().intValue() * ruleIds.size());
					jfSum = jfSum + (ruleLog.getGiveNum() == null ? 0 : ruleLog.getGiveNum().intValue());
				} else if (ShowType.GIVE_TOPUP_BALANCE.toString().equals(ruleLog.getShowType())) {
					// storeValue = ArithUtil.add(storeValue, ArithUtil.mul(ruleLog.getGiveNum(), new BigDecimal(ruleIds.size())));
					storeValue = ArithUtil.add(storeValue, ruleLog.getGiveNum());
					
				}
				ruleSetUseLogId.add(ruleLog.getId());
			}
		}
		// 将用户使用的充值积分返回
		balanceRecordService.updateBalance(payOrder.getCreateMemberId(), payOrder.getSysId(), sysUserId == null ? payOrder.getCreateMemberId() : sysUserId,
				sysUserId == null ? payOrder.getCreateMemberId() : sysUserId, ArithUtil.mul(new BigDecimal(-1), storeValue), balanceType, "账户余额回收", "订单号", oi.getOrderNo(),
				BalanceRecord.IS_BUY_NO);
		
		integralRecordService.addIntegralRecord(payOrder.getCreateMemberId(), payOrder.getSysId(), sysUserId == null ? payOrder.getCreateMemberId() : sysUserId,
				sysUserId == null ? payOrder.getCreateMemberId() : sysUserId, -1 * jfSum, integralType, "退款积分回收", "订单号", oi.getOrderNo(), IntegralRecord.IS_BUY_NO);
		// 修改日志为已回收
		if (logList != null && !logList.isEmpty()) {
			ruleSetUseLogMapper.updateIsGiving(ruleSetUseLogId, RuleSetUseLog.IS_RECOVERY_YES_2);
		}
		// 回收红包// 回收红包
		// redPacketService.updateOrderSend(oi.getId(), oi.getCreateMemberId());
		Map<Long, Integer> map = new HashMap<>();// 修改红包派发已使用的数量
		List<RedPacket> recRedList = redPacketService.selectOrderSend(oi.getId(), oi.getCreateMemberId());
		if (recRedList != null && !recRedList.isEmpty()) {
			for (RedPacket rp : recRedList) {
				rp.setMemberId(null);
				rp.setPayoutId(null);
				rp.setPayoutTime(null);
				rp.setStatus(RedPackStatus.INACTIVE);
				rp.setDrawMemberId(null);
				rp.setSendOrderId(null);
				rp.setUpdateTime(DateUtils.getCurrentDateTime());
				if (rp.getCreateRuleId() != null) {
					map.put(rp.getCreateRuleId(), (map.get(rp.getCreateRuleId()) == null ? 0 : map.get(rp.getCreateRuleId())) + 1);
				}
			}
			redPacketService.batchUpdate(recRedList);
			Set<Long> ruleSetId = map.keySet();
			if (ruleSetId.size() > 0) {
				for (Long id : ruleSetId) {
					ruleSetService.modityUseNumByRuleSet(id, -1 * (map.get(id)));
				}
			}
		}
		
	}
	
	/*
	 * 主订单确认收货
	 * 
	 * 
	 */
	@Override
	@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
	public Result<Map<String, Object>> confimReceipt(Long memberId, Long sysId, Long sysUserId, String orderNo, String ip, Result<Map<String, Object>> result, String remark)
			throws CustomException {
		
		OrderInfo orderInfo = orderInfoMap.findOrderInfoByOrderNo(orderNo);
		if (orderInfo != null) {
			
			// 用户确认收货
			if (sysUserId == null) {
				if (!memberId.equals(orderInfo.getCreateMemberId())) {
					result.setErrorCode(ErrorCode.MEMBER_ID_IS_ERROR);
					return result;
				}
				if (!sysId.equals(orderInfo.getSysId())) {
					result.setErrorCode(ErrorCode.SYS_ID_IS_ERROR);
					return result;
				}
			}
			
			if (OrderStatusEnum.已发货.getValue().equals(orderInfo.getOrderStatus())) {
				
				// 修改订单状态完成
				updateOrderStatus(orderNo, OrderStatusEnum.订单完成.getIndex(), sysUserId, orderInfo.getCreateMemberId(), remark, ip, null);
				// 赠送购物车---------------------------------------
				giftGivingService.doGiftGiving(orderInfo.getId(), orderInfo.getCreateMemberId(), orderInfo.getSysId(), TimeDotType.ORDER_COMPLETE, orderInfo.getOrderNo());
				
				// 赠送积分
				integralRecordService.addIntegralRecord(orderInfo.getCreateMemberId(), orderInfo.getSysId(), orderInfo.getCreateId(), orderInfo.getUpdateId(),
						orderInfo.getGiveJfSum(), com.zuipin.enums.IntegralType.GET_SHOPPING, "购物", "订单号", orderInfo.getOrderNo(), IntegralRecord.IS_BUY_NO);
				
				// 会员增加成长值
				// 累计消费=订单金额之和（订单金额=商品总价+运费-优惠）
				PayOrder payOrder = payOrderService.findPayOrderById(orderInfo.getPaymentOrderId());
				// 货到付款前任收货的时候，修改支付状态
				if (PayType.CASH_DELIVERY.toString().equals(payOrder.getPayType())) {
					payOrder.setPayStatus(PayOrder.YES);
					payOrder.setConfimPayTime(DateUtils.getCurrentDateTime());
					payOrder.setConfimSysUserId(sysUserId);
					payOrder.setUpdateTime(DateUtils.getCurrentDateTime());
					payOrderMapper.updateByPrimaryKey(payOrder);
				}
				// 订单金额之和（订单金额=商品总价+运费-优惠）
				BigDecimal totalAmount = ArithUtil.add(payOrder.getOrderSum(), payOrder.getUseStoreValue(), 2);
				memberAccountService.updateConsumption(memberId, sysId, totalAmount, orderInfo.getGrowthValue(), true, "购物", "订单号", orderInfo.getOrderNo(), sysUserId,
						GrowthValType.BUY_USE);
				
				// 本地事务执行完毕，调用第三方确认收货
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("sysName", OrderInfo.ZP_SYS_NANE);// 要根据systemId来判断哪个系统 醉品传 zuipin
				map.put("omsSubOrderId", orderInfo.getOrderNo());
				map.put("orderStatus", OrderInfo.OMS_ORDER_SUCCESS);// oms用 4 表示订单完成
				String content = JSONObject.toJSONString(map);
				log.info("确认收货请求参数：：" + content);
				String omsResult = HttpUtil.post(confimReceiptUrl, "requestData", content);
				log.info("oms 返回参数为 ：：" + omsResult);
				JSONObject json = JSONObject.parseObject(omsResult);
				if (json != null && json.get(ConstantsUtil.SUCCESS) != null && json.getBoolean(ConstantsUtil.SUCCESS)) {
					// 确认收货发消息给worker
					orderInfo.setOrderStatus(OrderStatusEnum.订单完成.getValue());
					rocketMQService.doSendSyncMsg(RocketMqInfo.SYSTEM_NAME + RocketMqInfo.PRODUCT_GROUP, RocketMqInfo.SYSTEM_NAME + RocketMqInfo.PRODUCT_NAME,
							RocketMqInfo.SYSTEM_NAME_WORKER, RocketMQTagEnum.ORDER_STATUS_CHANGE_RECEIVE + "", CommonUtils.getUUID(),
							com.alibaba.fastjson.JSONArray.toJSONString(orderInfo, SerializerFeature.WriteMapNullValue));
					
					result.setErrorCode(ErrorCode.SUCCESS);
				} else {
					throw new CustomException(ErrorCode.ORDER_ERRPR.getCode(), "oms订单完成失败!");
				}
			} else {
				throw new CustomException(ErrorCode.ORDER_FINISH_IN_DELIVERY.getCode(), "已发货的才能订单完成!");
			}
		} else {
			throw new CustomException(ErrorCode.ORDER_IS_NOT_EXIST.getCode(), "订单不存在!");
		}
		
		return result;
	}
	
	/**
	 * 客服后台修改订单
	 * @throws CustomException 
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public Result modityOrder(OrderInfoVo newOrderInfo, OrderConsigneeVo newConsignee, Long updateId, String ip, Result res) throws CustomException {
		// OrderInfo orderInfo = orderInfoMap.findOrderInfoByOrderNo(newOrderInfo.getOrderNo());
		// if (orderInfo != null) {
		editOrder(newOrderInfo, newConsignee, ip, updateId, OrderInfo.SYSTEM_UPDATE);
		/*} else {
			throw new CustomException(ErrorCode.ORDER_ERRPR.getCode(), "查无订单");
		}*/
		return res;
	}
	
	/**
	 * @Description:修改订单的收货地址及运费,配送信息，客服备注，订单备注
	 * @Title:
	 * @author: xujinding
	 * @date: 2017年3月27日下午1:53:08
	 */
	/** 
	 * @Title: editOrder 
	 * @Description: TODO
	 * @author xjd
	 * @param @param newOrderInfo
	 * @param @param newConsignee
	 * @param @param ip
	 * @param @param sysUserId
	 * @param @param memberOrSystem
	 * @param @throws CustomException
	 * @return void
	 * @throws 
	 */
	@Transactional(rollbackFor = Exception.class)
	public void editOrder(OrderInfoVo newOrderInfo, OrderConsigneeVo newConsignee, String ip, Long sysUserId, Integer memberOrSystem) throws CustomException {
		String modInfo = "";
		if (newOrderInfo == null) {
			throw new CustomException(ErrorCode.ILLEGAL_PARAM.getCode(), "参数错误");
		}
		
		OrderInfo oldOrderInfo = orderInfoMap.findOrderInfoByOrderNo(newOrderInfo.getOrderNo());
		if (oldOrderInfo == null) {
			throw new CustomException(ErrorCode.ORDER_ERRPR.getCode(), "查无订单");
		}
		Long consigneeId = oldOrderInfo.getConsigneeId();
		OrderConsignee preConsignee = orderConsigneeMapper.selectByPrimaryKey(consigneeId);
		
		/*		if (!(OrderStatusEnum.待审核.getValue().equals(oldOrderInfo.getOrderStatus())
						|| OrderStatusEnum.支付成功待审核.getValue().equals(oldOrderInfo.getOrderStatus())
						|| OrderStatusEnum.待付款.getValue().equals(oldOrderInfo.getOrderStatus()))) {
					throw new CustomException(ErrorCode.ORDER_ERRPR.getCode(), "只有付款成功待审核，待审核，待付款的订单才能修改");
				}*/
		// 判断是否修改发票信息
		if (newOrderInfo != null && newOrderInfo.getOrderInvoiceInfo() != null) {
			OrderInvoiceInfo orderInvoiceInfo = newOrderInfo.getOrderInvoiceInfo();
			if (orderInvoiceInfo.getId() == null) {
				orderInvoiceInfo.setCreateId(sysUserId);
				orderInvoiceInfo.setCreateTime(DateUtils.getCurrentDateTime());
				orderInvoiceInfo.setUpdateId(sysUserId);
				orderInvoiceInfo.setUpdateTime(DateUtils.getCurrentDateTime());
				orderInvoiceInfo.setDelFlag(ConstantsUtil.DEL_FLAG_NO_0);
				orderInvoiceInfo.setExpressStatus(OrderInvoiceInfo.STATUS_NO);
				orderInvoiceInfo.setInvoiceStatus(OrderInvoiceInfo.STATUS_NO);
				orderInvoiceInfoMapper.insertSelective(orderInvoiceInfo);
				
				PayOrder payOrder = new PayOrder();
				payOrder.setId(oldOrderInfo.getPaymentOrderId());
				payOrder.setInvoiceInfoId(orderInvoiceInfo.getId());
				payOrder.setUpdateId(sysUserId);
				payOrder.setUpdateTime(DateUtils.getCurrentDateTime());
				payOrderMapper.updateByPrimaryKeySelective(payOrder);
				
				OrderInfo tempOrderInfo = new OrderInfo();
				tempOrderInfo.setInvoiceInfoId(payOrder.getInvoiceInfoId());
				tempOrderInfo.setId(oldOrderInfo.getId());
				orderInfoMap.updateByPrimaryKeySelective(tempOrderInfo);
				
			} else {
				
				OrderInvoiceInfo temp = orderInvoiceInfoMapper.selectByPrimaryKey(orderInvoiceInfo.getId());
				temp.setInvoiceTitle(orderInvoiceInfo.getInvoiceTitle());
				temp.setInvoiceType(orderInvoiceInfo.getInvoiceType());
				temp.setInvoiceContent(orderInvoiceInfo.getInvoiceContent());
				temp.setCompanyName(orderInvoiceInfo.getCompanyName());
				temp.setEmail(orderInvoiceInfo.getEmail());
				temp.setTaxpayersNo(orderInvoiceInfo.getTaxpayersNo());
				temp.setOpenAccount(orderInvoiceInfo.getOpenAccount());
				temp.setOpenBank(orderInvoiceInfo.getOpenBank());
				temp.setUpdateTime(DateUtils.getCurrentDateTime());
				temp.setUpdateId(sysUserId);
				temp.setCompanyName(orderInvoiceInfo.getCompanyName());
				temp.setRegisterAddress(orderInvoiceInfo.getRegisterAddress());
				temp.setRegisterMobilePhone(orderInvoiceInfo.getRegisterMobilePhone());
				
				orderInvoiceInfoMapper.updateByPrimaryKey(temp);
				/*if (temp != null) {
					orderInvoiceInfo.setCreateId(temp.getCreateId());
					orderInvoiceInfo.setCreateTime(temp.getCreateTime());
					orderInvoiceInfo.setDelFlag(temp.getDelFlag());
					orderInvoiceInfo.setUpdateId(sysUserId);
					orderInvoiceInfo.setUpdateTime(DateUtils.getCurrentDateTime());
					orderInvoiceInfoMapper.updateByPrimaryKey(orderInvoiceInfo);
				}*/
			}
		}
		
		/* 均摊优惠价格 */
		PayOrder payOrder = payOrderMapper.selectByPrimaryKey(oldOrderInfo.getPaymentOrderId());
		if (!(PayOrder.YES.equals(payOrder.getPayStatus())) && (OrderStatusEnum.待审核.getValue().equals(oldOrderInfo.getOrderStatus()))
				|| OrderStatusEnum.待付款.getValue().equals(oldOrderInfo.getOrderStatus())) {
			// 判断是否修有内部优惠价
			if (newOrderInfo.getInternalDiscountSum() != null) {
				updateInternalDiscountSum(newOrderInfo.getInternalDiscountSum(), oldOrderInfo, payOrder, sysUserId);
			}
			
		}
		// else {
		// throw new CustomException(ErrorCode.ORDER_PAY_FINISH.getCode(), "已支付不能修改内部优惠");
		// }
		
		// 判断收货地址是否要更新
		if (!StringUtil.isEqualNull(preConsignee.getReceiptName(), newConsignee.getReceiptName()) || !StringUtil.isEqualNull(preConsignee.getAddress(), newConsignee.getAddress())
				|| !StringUtil.isEqualNull(preConsignee.getPhone(), newConsignee.getPhone()) || !StringUtil.isEqualNull(preConsignee.getTelephone(), newConsignee.getTelephone())) {
			if (OrderStatusEnum.待审核.getValue().equals(oldOrderInfo.getOrderStatus()) || OrderStatusEnum.支付成功待审核.getValue().equals(oldOrderInfo.getOrderStatus())
					|| OrderStatusEnum.待付款.getValue().equals(oldOrderInfo.getOrderStatus())) {
				preConsignee.setReceiptName(newConsignee.getReceiptName());
				preConsignee.setAddress(newConsignee.getAddress());
				preConsignee.setProvinceCode(newConsignee.getProvinceCode());
				preConsignee.setCityCode(newConsignee.getCityCode());
				preConsignee.setCountyCode(newConsignee.getCountyCode());
				preConsignee.setStreetAddress(newConsignee.getStreetAddress());
				preConsignee.setPhone(newConsignee.getPhone());
				preConsignee.setTelephone(newConsignee.getTelephone());
				preConsignee.setUpdateId(sysUserId);
				preConsignee.setUpdateTime(DateUtils.getCurrentDateTime());
				orderConsigneeMapper.updateByPrimaryKey(preConsignee);
				modInfo += "修改收货人信息,";
			} else {
				throw new CustomException(ErrorCode.ORDER_ERRPR.getCode(), "只有付款成功待审核，待审核，待付款的订单才能修改收货人信息");
			}
		}
		// 配送信息
		String newExpressDeliveryCode = newOrderInfo.getExpressDeliveryCode();
		String oldExpressDeliveryCode = oldOrderInfo.getExpressDeliveryCode();
		if (!StringUtil.isEqualNull(oldExpressDeliveryCode, newExpressDeliveryCode)) {
			// payOrder = payOrderMapper.selectByPrimaryKey(oldOrderInfo.getPaymentOrderId());
			
			if (!(PayOrder.YES.equals(payOrder.getPayStatus())) && (OrderStatusEnum.待审核.getValue().equals(oldOrderInfo.getOrderStatus()))
					|| OrderStatusEnum.待付款.getValue().equals(oldOrderInfo.getOrderStatus())) {
				
				OrderInfo tempOrderInfo = new OrderInfo();
				tempOrderInfo.setExpressDeliveryName(newOrderInfo.getExpressDeliveryName());
				tempOrderInfo.setExpressDeliveryCode(newOrderInfo.getExpressDeliveryCode());
				tempOrderInfo.setUpdateTime(DateUtils.getCurrentDateTime());
				tempOrderInfo.setUpdateId(sysUserId);
				tempOrderInfo.setId(oldOrderInfo.getId());
				orderInfoMap.updateByPrimaryKeySelective(tempOrderInfo);
				modInfo += "修改了配送信息，";
			} else {
				throw new CustomException(ErrorCode.ORDER_ERRPR.getCode(), "只有未支付,待审核才能修改配送信息");
			}
			
		}
		// 订单备注 //2016.6.6 备注不判断状态
		String newOrderRemark = newOrderInfo.getOrderRemark();
		String oldOrderRemark = oldOrderInfo.getOrderRemark();
		if (!StringUtil.isEqualNull(newOrderRemark, oldOrderRemark)) {
			/*if (OrderStatusEnum.待审核.getValue().equals(oldOrderInfo.getOrderStatus())
					|| OrderStatusEnum.支付成功待审核.getValue().equals(oldOrderInfo.getOrderStatus())
					|| OrderStatusEnum.待付款.getValue().equals(oldOrderInfo.getOrderStatus())) {*/
			OrderInfo tempOrderInfo = new OrderInfo();
			tempOrderInfo.setOrderRemark(newOrderRemark);
			tempOrderInfo.setUpdateTime(DateUtils.getCurrentDateTime());
			tempOrderInfo.setUpdateId(sysUserId);
			tempOrderInfo.setId(oldOrderInfo.getId());
			orderInfoMap.updateByPrimaryKeySelective(tempOrderInfo);
			modInfo += "修改了订单备注，";
			/*			} else {
							// 已支付不能修改运费
							throw new CustomException(ErrorCode.ORDER_ERRPR.getCode(),
									"只有待审核/付款成功待审核/待付款的订单才能修改订单备注");
						}*/
		}
		
		// 客服备注
		String newCustomerRemark = newOrderInfo.getCustomerRemark();
		String oldCustomerRemark = oldOrderInfo.getCustomerRemark();
		if (!StringUtil.isEqualNull(newCustomerRemark, oldCustomerRemark)) {
			/*			if (OrderStatusEnum.待审核.getValue().equals(oldOrderInfo.getOrderStatus())
								|| OrderStatusEnum.支付成功待审核.getValue().equals(oldOrderInfo.getOrderStatus())
								|| OrderStatusEnum.待付款.getValue().equals(oldOrderInfo.getOrderStatus())) {*/
			/// oldOrderInfo.setCustomerRemark(newCustomerRemark);
			/// oldOrderInfo.setUpdateTime(DateUtils.getCurrentDateTime());
			/// oldOrderInfo.setUpdateId(sysUserId);
			OrderInfo tempOrderInfo = new OrderInfo();
			tempOrderInfo.setCustomerRemark(newCustomerRemark);
			tempOrderInfo.setUpdateTime(DateUtils.getCurrentDateTime());
			tempOrderInfo.setUpdateId(sysUserId);
			tempOrderInfo.setId(oldOrderInfo.getId());
			orderInfoMap.updateByPrimaryKeySelective(tempOrderInfo);
			modInfo += "修改了客服备注，";
			/*			} else {
							// 已支付不能修改运费
							throw new CustomException(ErrorCode.ORDER_ERRPR.getCode(), "只有待审核/待付款的订单才能修改客服备注");
						}*/
		}
		
		// 判断有修改运费
		BigDecimal oldfreight = oldOrderInfo.getFreightSum() == null ? BigDecimal.valueOf(0) : oldOrderInfo.getFreightSum();
		BigDecimal newfreight = newOrderInfo.getFreightSum() == null ? BigDecimal.valueOf(0) : newOrderInfo.getFreightSum();
		if (oldfreight.doubleValue() > newfreight.doubleValue() || oldfreight.doubleValue() < newfreight.doubleValue()) {
			// payOrder = payOrderMapper.selectByPrimaryKey(oldOrderInfo.getPaymentOrderId());
			if (!(PayOrder.YES.equals(payOrder.getPayStatus())) && (OrderStatusEnum.待审核.getValue().equals(oldOrderInfo.getOrderStatus()))
					|| OrderStatusEnum.待付款.getValue().equals(oldOrderInfo.getOrderStatus())) {
				
				/*				payOrder.setFreightSum(newfreight);
								payOrder.setOrderSum(ArithUtil.add(ArithUtil.sub(payOrder.getOrderSum(), oldfreight), newfreight));
								payOrder.setVersionFreight(payOrder.getVersionFreight() + 1L);
								payOrder.setUpdateId(sysUserId);
								payOrder.setUpdateTime(DateUtils.getCurrentDateTime());
								*/
				PayOrder tempPayOrder = new PayOrder();
				tempPayOrder.setFreightSum(newfreight);
				tempPayOrder.setOrderSum(ArithUtil.add(ArithUtil.sub(payOrder.getOrderSum(), oldfreight), newfreight));
				tempPayOrder.setVersionFreight(payOrder.getVersionFreight() + 1L);
				tempPayOrder.setUpdateId(sysUserId);
				tempPayOrder.setUpdateTime(DateUtils.getCurrentDateTime());
				tempPayOrder.setId(payOrder.getId());
				OrderInfo tempOrderInfo = new OrderInfo();
				tempOrderInfo.setOrderSum(ArithUtil.add(ArithUtil.sub(oldOrderInfo.getOrderSum(), oldfreight), newfreight));
				tempOrderInfo.setFreightSum(newfreight);
				tempOrderInfo.setUpdateId(sysUserId);
				tempOrderInfo.setUpdateTime(DateUtils.getCurrentDateTime());
				tempOrderInfo.setId(oldOrderInfo.getId());
				/*	oldOrderInfo.setOrderSum(ArithUtil.add(ArithUtil.sub(oldOrderInfo.getOrderSum(), oldfreight), newfreight));
					oldOrderInfo.setFreightSum(newfreight);
					oldOrderInfo.setUpdateId(sysUserId);
					oldOrderInfo.setUpdateTime(DateUtils.getCurrentDateTime());*/
				orderInfoMap.updateByPrimaryKeySelective(tempOrderInfo);
				payOrderMapper.updateByPrimaryKeySelective(tempPayOrder);
				modInfo += "修改了运费，";
			} else {
				// 已支付不能修改运费
				throw new CustomException(ErrorCode.ORDER_ERRPR.getCode(), "已支付不能修改运费");
			}
		}
		
		if (StringUtil.isNotBlank(modInfo)) {
			OrderInfoLog orderInfoLog = new OrderInfoLog();
			orderInfoLog.setCreateTime(DateUtils.getCurrentDateTime());
			// orderInfoLog.setIpAddress(ip);
			orderInfoLog.setSysUserId(sysUserId);
			orderInfoLog.setUpdateInfo(modInfo);
			orderInfoLog.setOrderNo(oldOrderInfo.getOrderNo());
			orderInfoLogMapper.insertSelective(orderInfoLog);
		}
	}
	
	/**
	 * 内部红包价格均摊
	 *
	 * @Title: updateInternalDiscountSum 
	 * @author: wuyicheng
	 * @date: 2017年6月28日上午10:08:12 
	 * @param internalDiscountSum 内部优惠价格
	 * @param oldOrderInfo 订单
	 * @param payOrder 付款单
	 * @param sysUserId 后台操作人ID
	 * @return: void
	 * @throws
	 */
	public void updateInternalDiscountSum(BigDecimal internalDiscountSum, OrderInfo oldOrderInfo, PayOrder payOrder, Long sysUserId) {
		// BigDecimal internalDiscountSum = newOrderInfo.getInternalDiscountSum();
		BigDecimal oldInternalDiscountSum = oldOrderInfo.getInternalDiscountSum();
		
		if (ArithUtil.compareTo(internalDiscountSum, oldInternalDiscountSum) != 0) {
			// 折前商品总价
			BigDecimal productPaySum = oldOrderInfo.getProductPaySum();
			
			List<OrderDetail> orderDetails = orderDetailMapper.findOrderDetailListByOrderId(oldOrderInfo.getId());
			
			for (OrderDetail orderDetail : orderDetails) {
				if (!(PremiumEnum.NO_PREMIUM.toString().equals(orderDetail.getPremiumEnum()))) {
					continue;
				}
				// 只更新实际支付价，商品内部优惠价
				BigDecimal buyNum = orderDetail.getProductNum();
				// BigDecimal productPrice = orderDetail.getProductPrice();
				// BigDecimal actualPayPrice = ArithUtil.add(orderDetail.getPurchasePrice(),
				// ArithUtil.div(orderDetail.getInternalDiscountSum(), buyNum, 6), 6);
				// 折前小计
				BigDecimal subtotal = orderDetail.getSubtotal();
				// 商品内部优惠小计
				BigDecimal useDiscountAmount = payOrderService.getUseDiscountAmount(subtotal, productPaySum, internalDiscountSum);
				// 实际支付小计(折前小计-红包优惠-规则优惠-内部优惠)
				BigDecimal actualPayPriceSum = ArithUtil.sub(ArithUtil.sub(ArithUtil.sub(subtotal, orderDetail.getUseRuleSum()), useDiscountAmount),
						orderDetail.getUseRedPacketSum(), 2);
				// 单个商品内部优惠小计
				// BigDecimal singleDiscountAmount = ArithUtil.div(useDiscountAmount, buyNum, 6);
				// BigDecimal afterPayPrice = ArithUtil.sub(actualPayPrice, singleDiscountAmount, 2);
				// 实付单价=实际支付小计/购买数量
				BigDecimal afterPayPrice = ArithUtil.div(actualPayPriceSum, buyNum, 4);
				orderDetail.setInternalDiscountSum(useDiscountAmount);
				orderDetail.setActualPaySubtotal(actualPayPriceSum);
				orderDetail.setPurchasePrice(afterPayPrice);
				orderDetail.setUpdateTime(DateUtils.getCurrentDateTime());
				orderDetail.setUpdateId(sysUserId);
				orderDetailMapper.updateByPrimaryKeySelective(orderDetail);
			}
			
			BigDecimal orderSum = ArithUtil.add(oldOrderInfo.getOrderSum(), oldInternalDiscountSum, 2);
			// 实付总金额
			orderSum = ArithUtil.sub(orderSum, internalDiscountSum, 2);
			
			// 更新付款单
			// PayOrder tempPayOrder = new PayOrder();
			payOrder.setId(oldOrderInfo.getPaymentOrderId());
			payOrder.setOrderSum(orderSum);
			payOrder.setVersionFreight(payOrder.getVersionFreight() + 1L);
			payOrder.setUpdateId(sysUserId);
			payOrder.setInternalDiscountSum(internalDiscountSum);
			payOrder.setUpdateTime(DateUtils.getCurrentDateTime());
			payOrderMapper.updateByPrimaryKeySelective(payOrder);
			
			Integer growthValue = ArithUtil.add(ArithUtil.sub(orderSum, oldOrderInfo.getFreightSum(), 2), payOrder.getUseStoreValue(), 2).intValue();
			
			oldOrderInfo.setOrderSum(orderSum);
			oldOrderInfo.setGrowthValue(growthValue);
			oldOrderInfo.setInternalDiscountSum(internalDiscountSum);
			oldOrderInfo.setUpdateTime(DateUtils.getCurrentDateTime());
			oldOrderInfo.setUpdateId(sysUserId);
			orderInfoMap.updateByPrimaryKeySelective(oldOrderInfo);
		}
		
	}
	
	/**
	 * @Description:查询OrderInfo分页
	 * @Title:
	 * @author: xujinding
	 * @date: 2017年3月27日下午1:53:08
	 */
	@Override
	public List<Map<String, Object>> findOrderInfoListByPage(OrderInfoVo orderInfo) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("order", orderInfo);
		List<Map<String, Object>> orderList = orderInfoMap.findOrderInfoByPage(map);
		return orderList;
	}
	
	/**
	 * @Description:审核订单
	 * @Title:
	 * @author: xujinding
	 * @throws CustomException 
	 * @throws ParseException 
	 * @date: 2017年3月27日下午1:53:08
	 */
	@Override
	@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
	public Result auditOrder(String orderNo, Long sysUserId, String ip, Result res) throws CustomException {
		OrderInfo oldOrderInfo = orderInfoMap.findOrderInfoByOrderNo(orderNo);
		if (oldOrderInfo != null) {
			if (OrderStatusEnum.待审核.getValue().equals(oldOrderInfo.getOrderStatus()) || OrderStatusEnum.支付成功待审核.getValue().equals(oldOrderInfo.getOrderStatus())) {
				// 查询unionId
				ThirdAccount thirdAccount = thirdAccountService.findByMemberId(oldOrderInfo.getCreateMemberId(), ThirdAccount.THIRD_PLAT_WECHAT, OrderInfo.ZP_SYS_ID);
				
				if (thirdAccount != null) {
					oldOrderInfo.setUnionId(thirdAccount.getUnionId());
				}
				updateOrderStatus(orderNo, OrderStatusEnum.处理中.getIndex(), sysUserId, null, "后台客服审核通过", ip, null);
				// 赠送购物车-------------------------------------
				giftGivingService.doGiftGiving(oldOrderInfo.getId(), oldOrderInfo.getCreateMemberId(), oldOrderInfo.getSysId(), PayType.CASH_DELIVERY, oldOrderInfo.getOrderNo());
				// 要流向订单系统 做拆单
				this.createOrderToOms(oldOrderInfo, sysUserId);
				// 发送消息给 worker
				oldOrderInfo.setOrderStatus(OrderStatusEnum.打包中.getValue());
				rocketMQService.doSendSyncMsg(RocketMqInfo.SYSTEM_NAME + RocketMqInfo.PRODUCT_GROUP, RocketMqInfo.SYSTEM_NAME + RocketMqInfo.PRODUCT_NAME,
						RocketMqInfo.SYSTEM_NAME_WORKER, RocketMQTagEnum.ORDER_STATUS_CHANGE_AUDIT + "", CommonUtils.getUUID(),
						com.alibaba.fastjson.JSONArray.toJSONString(oldOrderInfo, SerializerFeature.WriteMapNullValue));
				// log.error("审核订单--发送消息给worker失败：：单号为" + oldOrderInfo.getOrderNo(), e);
				
				res.setErrorCode(ErrorCode.SUCCESS);
			} else {
				res.setErrorCode(ErrorCode.ORDER_ERRPR);
				res.setMessage("只有待审核或付款成功待审核才能审核通过");
			}
		} else {
			res.setErrorCode(ErrorCode.ORDER_ERRPR);
			res.setMessage("查无订单");
		}
		return res;
	}
	
	/**
	 * 后台订单列表
	 */
	@Override
	public Map<String, Object> backOrderList(OrderSerachVo orderSerachVo) {
		Pagination page = new Pagination();
		page.setPageNumber(orderSerachVo.getPageNumber());
		page.setPageSize(orderSerachVo.getPageSize());
		String group = orderSerachVo.getTreeOrderStatus();
		// 处理分组 开始
		List<OrderStatusEnum> groupStatus = OrderStatusEnum.getStatusList(group);
		List<String> tempTreeOrderStatus = new ArrayList<String>();
		String tempTree = "";
		for (int i = 0; i < groupStatus.size(); i++) {
			// tempTreeOrderStatus.add(groupStatus.get(i).getValue());
			if (i == groupStatus.size() - 1) {
				tempTree += groupStatus.get(i).getValue();
			} else {
				tempTree += groupStatus.get(i).getValue() + ",";
			}
		}
		orderSerachVo.setTreeOrderStatus(addQuotes(tempTree));
		// 处理分组 结束
		String status = orderSerachVo.getOrderStatus();
		String[] arrayStatus = CommonUtils.splitBySymbol(status, ",");
		orderSerachVo.setOrderStatus(addQuotes(status));
		List<Map<String, Object>> list = orderInfoMap.findBackListOrderByPage(orderSerachVo, tempTreeOrderStatus, arrayStatus, page);
		if (list != null && list.size() > 0) {
			List<Long> memberIds = new ArrayList<Long>();
			for (Map<String, Object> map : list) {
				memberIds.add(Convert.toLong(map.get("createMemberId")));
			}
			List<Member> members = memberService.findListMember(memberIds);
			Map<Long, Member> memberMap = new HashMap<>();
			for (Member mem : members) {
				memberMap.put(mem.getId(), mem);
			}
			// contactName,createMemberPhone
			for (Map<String, Object> map : list) {
				Member mem = memberMap.get(Convert.toLong(map.get("createMemberId")));
				if (mem != null) {
					map.put("contactName", mem.getContactName());
					map.put("createMemberPhone", mem.getPhone());
				}
			}
		}
		Map<String, Object> returnMap = new HashMap<String, Object>();
		returnMap.put("orderList", list);
		returnMap.put("orderNum", page.getTotalRecord());
		return returnMap;
	}
	
	/**
	 * 前台根据状态查询订单列表
	 */
	/* (non-Javadoc)
	 * @see com.zuipin.service.IOrderService#preOrderList(java.lang.String, java.lang.Long, java.lang.Long, int, int, java.lang.String)
	 */
	@Override
	public Map<String, Object> preOrderList(String orderStatus, Long memberId, Long systemId, int pageNumber, int pageSize, String device) {
		Pagination page = new Pagination();
		page.setPageSize(pageSize);
		page.setPageNumber(pageNumber);
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("orderStatus", orderStatus);
		param.put("systemId", systemId);
		param.put("memberId", memberId);
		List<Map<String, Object>> list = orderInfoMap.preOrderList(param, page);
		// 拼接详情
		
		for (Map<String, Object> item : list) {
			List<ProductExtVo> productExtList = new ArrayList<ProductExtVo>();
			Long orderId = Long.valueOf(String.valueOf(item.get("orderId")));
			List<OrderDetail> odList = orderDetailMapper.findOrderDetailListByOrderId(orderId);
			for (OrderDetail od : odList) {
				ProductExtVo pvo = new ProductExtVo();
				pvo.setProSku(od.getProSku());
				productExtList.add(pvo);
			}
			ProExtSerachVo svo = new ProExtSerachVo();
			svo.setDevice(device);
			svo.setMemberId(memberId);
			svo.setSysId(systemId);
			svo.setProductExtList(productExtList);
			svo.setShowOffShelf(false);
			Map<String, ProExtInfoVo> proMap = productInfoService.queryProExtInfo(svo);
			for (OrderDetail od : odList) {
				ProExtInfoVo pevo = proMap.get(od.getProSku());
				if (pevo != null) {
					od.setImageUrl(pevo.getProImg());
				}
			}
			item.put("products", odList);
		}
		
		// 要拼接商品
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("orderNum", page.getTotalRecord());
		map.put("order", list);
		return map;
	}
	
	/**
	 * 各个订单状态的数量
	 */
	@Override
	public Map<String, Integer> findStatusNum(Long memberId, Long systemId) {
		Map<String, Integer> returnMap = new HashMap<String, Integer>();
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("systemId", systemId);
		param.put("memberId", memberId);
		List<Map<String, Object>> list = orderInfoMap.findStatusNum(param);
		// 查询待评价 订单 的个数
		Integer waitCommentNum = orderInfoMap.findWaitNumNum(param);
		returnMap.put("waitCommentNum", waitCommentNum);
		if (list != null && list.size() > 0) {
			for (Map<String, Object> map : list) {
				
				if (OrderStatusEnum.待付款.getValue().equals(map.get("orderStatus"))) {
					returnMap.put("waitPay", Integer.valueOf(String.valueOf(map.get("num"))));
				}
				
				if (OrderStatusEnum.已发货.getValue().equals(map.get("orderStatus"))) {
					returnMap.put("send", Integer.valueOf(String.valueOf(map.get("num"))));
				}
				
				if (OrderStatusEnum.订单完成.getValue().equals(map.get("orderStatus"))) {
					returnMap.put("success", Integer.valueOf(String.valueOf(map.get("num"))));
				}
				
				if (OrderStatusEnum.处理中.getValue().equals(map.get("orderStatus"))) {
					returnMap.put("dealing", Integer.valueOf(String.valueOf(map.get("num"))));
				}
				if (OrderStatusEnum.打包中.getValue().equals(map.get("orderStatus"))) {
					returnMap.put("packing", Integer.valueOf(String.valueOf(map.get("num"))));
				}
				
				if (OrderStatusEnum.待审核.getValue().equals(map.get("orderStatus"))) {
					returnMap.put("waitAudit", Integer.valueOf(String.valueOf(map.get("num"))));
				}
				
				if (OrderStatusEnum.支付成功待审核.getValue().equals(map.get("orderStatus"))) {
					returnMap.put("paySuccessWaitAudit", Integer.valueOf(String.valueOf(map.get("num"))));
				}
			}
		}
		
		if (returnMap.get("waitAudit") == null) {
			returnMap.put("waitAudit", 0);
		}
		if (returnMap.get("packing") == null) {
			returnMap.put("packing", 0);
		}
		if (returnMap.get("success") == null) {
			returnMap.put("success", 0);
		}
		if (returnMap.get("send") == null) {
			returnMap.put("send", 0);
		}
		if (returnMap.get("waitPay") == null) {
			returnMap.put("waitPay", 0);
		}
		
		if (returnMap.get("dealing") == null) {
			returnMap.put("dealing", 0);
		}
		if (returnMap.get("paySuccessWaitAudit") == null) {
			returnMap.put("paySuccessWaitAudit", 0);
		}
		return returnMap;
	}
	
	/**
	 * 订单商品数量
	 * @throws Exception 
	 */
	@Override
	public JSONObject orderProductList(Long orderId, String device, Long memberId) throws CustomException {
		OrderInfo orderInfo = orderInfoMap.selectByPrimaryKey(orderId);
		
		JSONObject json = new JSONObject();
		JSONObject returnJson = new JSONObject();
		if (orderInfo != null) {
			if (memberId != null) {
				if (!memberId.equals(orderInfo.getCreateMemberId())) {
					throw new CustomException(ErrorCode.ORDER_ERRPR.getCode(), "订单与会员不匹配");
				}
			}
			if (OrderStatusEnum.待审核.getValue().equals(orderInfo.getOrderStatus()) || OrderStatusEnum.支付成功待审核.getValue().equals(orderInfo.getOrderStatus())
					|| OrderStatusEnum.待付款.getValue().equals(orderInfo.getOrderStatus()) || OrderStatusEnum.已取消.getValue().equals(orderInfo.getOrderStatus())
					|| OrderStatusEnum.处理中.getValue().equals(orderInfo.getOrderStatus())) {
				// 查询主订单
				returnJson.put("mainrNo", orderInfo.getOrderNo());
				returnJson.put("mainOrderStatus", orderInfo.getOrderStatus());
				returnJson.put("subSendRepertory", "");
				returnJson.put("expressNo", "");
				returnJson.put("expressCode", "");
				returnJson.put("expressName", "");
				List<OrderDetail> odList = orderDetailMapper.findOrderDetailListByOrderId(orderInfo.getId());
				List<ProductExtVo> productExtList = new ArrayList<ProductExtVo>();
				for (OrderDetail od : odList) {
					ProductExtVo pvo = new ProductExtVo();
					pvo.setProSku(od.getProSku());
					productExtList.add(pvo);
				}
				ProExtSerachVo svo = new ProExtSerachVo();
				svo.setDevice(device);
				svo.setMemberId(orderInfo.getCreateMemberId());
				svo.setSysId(orderInfo.getSysId());
				svo.setProductExtList(productExtList);
				svo.setShowOffShelf(false);
				Map<String, ProExtInfoVo> proMap = productInfoService.queryProExtInfo(svo);
				for (OrderDetail od : odList) {
					
					ProExtInfoVo pevo = proMap.get(od.getProSku());
					if (pevo != null) {
						od.setImageUrl(pevo.getProImg());
					}
					
				}
				returnJson.put("products", odList);
				json.put("mainOrder", returnJson);
				json.put("subOrder", null);
			} else {
				// 先查子订单 wms
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("orderNo", orderInfo.getOrderNo());
				String wmsResult = "";
				try {
					wmsResult = HttpUtil.post(finsSubOrderUrl, param, 0, 0);
				} catch (Exception e) {
					log.error("查询wms失败：：" + e.getMessage());
				}
				if (StringUtil.isNotBlank(wmsResult)) {
					
					JSONObject obj = JSONObject.parseObject(wmsResult);
					
					if (ErrorCode.SUCCESS.getCode() == obj.getInteger("code")) {
						JSONArray array = obj.getJSONArray("data");
						if (array == null || array.size() < 1) {
							setMainOrderInfo(orderInfo, returnJson, json, device);
						} else {
							
							returnJson.put("subOrderNo", String.valueOf(array.getJSONObject(0).get("subOrderNo")));
							returnJson.put("subOrderStatus", String.valueOf(array.getJSONObject(0).get("subOrderStatus")));
							returnJson.put("subSendRepertory", String.valueOf(array.getJSONObject(0).get("subSendRepertory")));
							returnJson.put("expressNo", String.valueOf(array.getJSONObject(0).get("expressNo")));
							returnJson.put("expressCode", String.valueOf(array.getJSONObject(0).get("expressCode")));
							returnJson.put("expressName", String.valueOf(array.getJSONObject(0).get("expressName")));
							
							List<OrderDetail> odList = orderDetailMapper.findOrderDetailListByOrderId(orderInfo.getId());
							returnJson = array.getJSONObject(0);
							List<ProductExtVo> productExtList = new ArrayList<ProductExtVo>();
							for (OrderDetail od : odList) {
								ProductExtVo pvo = new ProductExtVo();
								pvo.setProSku(od.getProSku());
								productExtList.add(pvo);
							}
							ProExtSerachVo svo = new ProExtSerachVo();
							svo.setDevice(device);
							svo.setMemberId(orderInfo.getCreateMemberId());
							svo.setSysId(orderInfo.getSysId());
							svo.setProductExtList(productExtList);
							Map<String, ProExtInfoVo> proMap = productInfoService.queryProExtInfo(svo);
							for (OrderDetail od : odList) {
								ProExtInfoVo pevo = proMap.get(od.getProSku());
								if (pevo != null) {
									od.setImageUrl(pevo.getProImg());
								}
							}
							returnJson.put("products", odList);
							json.put("subOrder", returnJson);
							json.put("mainOrder", null);
						}
					} else {
						setMainOrderInfo(orderInfo, returnJson, json, device);
					}
				} else {
					setMainOrderInfo(orderInfo, returnJson, json, device);
				}
			}
		} else {
			throw new CustomException(ErrorCode.ORDER_ERRPR.getCode(), "查无订单");
		}
		return json;
	}
	
	/**
	 * 设置主订单
	* @Description:
	* @Title: 
	* @author: xujinding
	* @date: 2017年5月18日上午11:59:04
	 */
	public void setMainOrderInfo(OrderInfo orderInfo, Map<String, Object> returnJson, Map<String, Object> json, String device) {
		returnJson.put("mainrNo", orderInfo.getOrderNo());
		returnJson.put("mainOrderStatus", orderInfo.getOrderStatus());
		returnJson.put("subSendRepertory", "");
		returnJson.put("expressNo", "");
		returnJson.put("expressCode", "");
		returnJson.put("expressName", "");
		
		List<OrderDetail> odList = orderDetailMapper.findOrderDetailListByOrderId(orderInfo.getId());
		List<ProductExtVo> productExtList = new ArrayList<ProductExtVo>();
		for (OrderDetail od : odList) {
			ProductExtVo pvo = new ProductExtVo();
			pvo.setProSku(od.getProSku());
			productExtList.add(pvo);
		}
		ProExtSerachVo svo = new ProExtSerachVo();
		svo.setDevice(device);
		svo.setMemberId(orderInfo.getCreateMemberId());
		svo.setSysId(orderInfo.getSysId());
		svo.setProductExtList(productExtList);
		svo.setShowOffShelf(false);
		Map<String, ProExtInfoVo> proMap = productInfoService.queryProExtInfo(svo);
		for (OrderDetail od : odList) {
			ProExtInfoVo pevo = proMap.get(od.getProSku());
			if (pevo != null) {
				od.setImageUrl(pevo.getProImg());
			}
		}
		returnJson.put("products", odList);
		json.put("mainOrder", returnJson);
		json.put("subOrder", null);
	}
	
	/**
	 * 根据订单编码查询订单信息（付款单跟主订单结合）
	 */
	@Override
	public Result getOrderAndPayInfoByOrderNo(String orderNo, Integer delYes, Long memberId) {
		Result res = new Result();
		if (StringUtil.isNotBlank(orderNo)) {
			Map<String, Object> paMap = new HashMap<String, Object>();
			paMap.put("orderNo", orderNo);
			paMap.put("delYes", delYes);
			paMap.put("memberId", memberId);
			Map<String, Object> map = orderInfoMap.getOrderAndPayInfoByOrderNo(paMap);
			if (map != null) {
				Object orderId = map.get("orderId");
				if (orderId != null) {
					List<RuleSetUserLogVo> RuleSetUserLogVo = ruleSetUseLogMapper.findByOrderIdAndShowType((long) orderId);
					map.put("fullCut", RuleSetUserLogVo);
				}
			}
			res.setData(map);
			res.setErrorCode(ErrorCode.SUCCESS);
		} else {
			res.setErrorCode(ErrorCode.ORDER_ERRPR);
			res.setMessage("参数为空");
		}
		return res;
	}
	
	/*
	 *sql  in  拼接单引号
	 */
	public String addQuotes(String status) {
		String tempStatus = "";
		String[] arrayStatus = CommonUtils.splitBySymbol(status, ",");
		if (arrayStatus != null) {
			for (int i = 0; i < arrayStatus.length; i++) {
				if (arrayStatus.length - 1 == i) {
					tempStatus += "'" + arrayStatus[i] + "'";
				} else {
					tempStatus += "'" + arrayStatus[i] + "'" + ",";
				}
			}
		}
		return tempStatus;
	}
	
	/**
	 * 关闭订单
	 * @throws Exception 
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Result closeOrder(String orderNo, Long sysUserId, String closeReason) throws CustomException {
		Result res = new Result();
		OrderInfo orderInfo = orderInfoMap.findOrderInfoByOrderNo(orderNo);
		if (orderInfo != null) {
			if (OrderStatusEnum.支付成功待审核.getValue().equals(orderInfo.getOrderStatus()) || OrderStatusEnum.处理中.getValue().equals(orderInfo.getOrderStatus())
					|| OrderStatusEnum.已发货.getValue().equals(orderInfo.getOrderStatus()) || OrderStatusEnum.打包中.getValue().equals(orderInfo.getOrderStatus())
					|| OrderStatusEnum.订单完成.getValue().equals(orderInfo.getOrderStatus())) {
				String status = orderInfo.getOrderStatus();
				
				// 处理积分优惠等
				PayOrder payOrder = payOrderMapper.selectByPrimaryKey(orderInfo.getPaymentOrderId());
				RedPacket redPacket = new RedPacket();
				redPacket.setId(payOrder.getUseRedPacketId());
				redPacket.setStatus(com.zuipin.enums.RedPackStatus.UNUSED);
				redPacket.setOrderNo(null);
				redPacket.setOrderId(null);
				redPacketService.update(redPacket);
				// 将使用的返给用户
				balanceRecordService.updateBalance(payOrder.getCreateMemberId(), payOrder.getSysId(), sysUserId, sysUserId, payOrder.getUseStoreValue(),
						com.zuipin.enums.BalanceType.CLOSE_BACK, "账户余额退回", "订单号", orderInfo.getOrderNo(), BalanceRecord.IS_BUY_NO);
				
				integralRecordService.addIntegralRecord(payOrder.getCreateMemberId(), payOrder.getSysId(), sysUserId, sysUserId, payOrder.getUseJfSum(),
						com.zuipin.enums.IntegralType.CLOSE_BACK, "积分退回", "订单号", orderInfo.getOrderNo(), IntegralRecord.IS_BUY_NO);
				
				int giveJfSum = 0;
				// 当订单已经派送过成长值和积分以后，关闭才需要退还积分，成长值
				if (OrderInfo.IS_GIVE_GROWTH_VALUE_YES_1 == orderInfo.getIsGiveGrowthValue()) {
					giveJfSum = orderInfo.getGiveJfSum() == null ? 0 : orderInfo.getGiveJfSum();
					// 如果发生订单关闭时，则需要倒扣该订单赠送的积分，同时扣除对应赠送的成长值
					/*integralRecordService.addIntegralRecord(payOrder.getCreateMemberId(), payOrder.getSysId(), sysUserId, sysUserId, -1 * orderInfo.getGiveJfSum(),
							IntegralType.ORDER_RECYCLING, "订单号:" + orderNo + "关闭订单回收积分");*/
					// 订单金额之和（订单金额=商品总价+运费-优惠）
					
					BigDecimal totalAmount = ArithUtil.add(payOrder.getOrderSum(), payOrder.getUseStoreValue(), 2);
					memberAccountService.updateConsumption(orderInfo.getCreateMemberId(), orderInfo.getSysId(), totalAmount, orderInfo.getGrowthValue(), false, "退款成长值回收", "订单号",
							orderNo, sysUserId, GrowthValType.REFUND);
				}
				// 回收 注意
				this.doRecoveryJfAndStore(orderInfo, payOrder, sysUserId, BalanceType.ORDER_RECYCLING, IntegralType.ORDER_RECYCLING, giveJfSum);
				
				updateOrderStatus(orderInfo.getOrderNo(), OrderStatusEnum.已关闭.getIndex(), sysUserId, null, "关闭订单操作", null, closeReason);
				// 订单完成不处理优惠
				// if (OrderStatusEnum.订单完成.getValue().equals(status)) {
				
				// integralRecordService.addIntegralRecord(payOrder.getCreateMemberId(),
				// payOrder.getSysId(), payOrder.getCreateMemberId(),
				// payOrder.getCreateMemberId(), payOrder.getGiveJfSum(),
				// com.zuipin.enums.IntegralType.ORDER_RECYCLING, "关闭订单回收送积分");
				// balanceRecordService.updateBalance(payOrder.getCreateMemberId(),
				// payOrder.getSysId(), payOrder.getCreateMemberId(),
				// payOrder.getCreateMemberId(), payOrder.getUseStoreValue(),
				// com.zuipin.enums.BalanceType.REFUND, "关闭订单返充值");
				// }
				if (OrderStatusEnum.支付成功待审核.getValue().equals(status)) {
					// 取消虚拟预占
					List<OrderDetail> orderDetails = orderDetailMapper.findOrderDetailListByOrderId(orderInfo.getId());
					boolean isHoldSuccess = payOrderService.preholdCisStock(orderDetails, PayOrder.PRE_RELEASE_STOCK, orderInfo, "关闭订单释放虚拟预占", sysUserId + "", payOrder.YES);
					if (!isHoldSuccess) {
						throw new CustomException(ErrorCode.ORDER_ERRPR.getCode(), "关闭订单释放虚拟预占失败,请检查cis有无该商品，或其他原因");
					}
				}
				
				if (OrderStatusEnum.处理中.getValue().equals(status)) {
					// 发给其他系统
					SysUser sysUser = sysUserService.findById(sysUserId);
					if (sysUser != null) {
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("sysName", OrderInfo.ZP_SYS_NANE);// 要根据systemId来判断哪个系统 醉品传 zuipin
						map.put("orderNo", orderInfo.getOrderNo());
						map.put("orderStatus", OrderStatusEnum.已关闭.getValue());
						map.put("operator", sysUser.getRealName());
						map.put("userId", sysUserId);
						String content = JSONObject.toJSONString(map).toString();
						String omsResult = HttpUtil.post(closeOrderUrl, "requestData", content);
						log.info("oms 返回参数为 ：：" + omsResult);
						JSONObject json = JSONObject.parseObject(omsResult);
						if (json != null && json.get("success") != null && json.getBoolean("success")) {
							// 不做处理
						} else {
							log.info("oms订单关闭失败");
							throw new CustomException(ErrorCode.ORDER_ERRPR.getCode(), "oms订单关闭失败::" + omsResult);
						}
					} else {
						
						res.setErrorCode(ErrorCode.ORDER_ERRPR);
						res.setMessage("查询不到操作人");
						return res;
					}
				}
				// 审核通过后做关闭要通知worker 待确认佣金要减掉
				// 处理中比较特殊，因为 oms做取消拆单户变成处理中
				if (OrderStatusEnum.处理中.getValue().equals(status) || OrderStatusEnum.已发货.getValue().equals(status) || OrderStatusEnum.订单完成.getValue().equals(status)
						|| OrderStatusEnum.打包中.getValue().equals(status)) {
					try {
						// 发送消息给 worker
						// 查询unionId
						ThirdAccount thirdAccount = thirdAccountService.findByMemberId(orderInfo.getCreateMemberId(), ThirdAccount.THIRD_PLAT_WECHAT, OrderInfo.ZP_SYS_ID);
						if (thirdAccount != null) {
							orderInfo.setUnionId(thirdAccount.getUnionId());
						}
						
						rocketMQService.doSendSyncMsg(RocketMqInfo.SYSTEM_NAME + RocketMqInfo.PRODUCT_GROUP, RocketMqInfo.SYSTEM_NAME + RocketMqInfo.PRODUCT_NAME,
								RocketMqInfo.SYSTEM_NAME_WORKER, RocketMQTagEnum.ORDER_STATUS_CHANGE_CLOSE + "", CommonUtils.getUUID(),
								com.alibaba.fastjson.JSONArray.toJSONString(orderInfo, SerializerFeature.WriteMapNullValue));
					} catch (Exception e) {
						log.error("关闭订单--发送消息给worker失败：：", e);
					}
				}
				res.setErrorCode(ErrorCode.SUCCESS);
			} else {
				res.setErrorCode(ErrorCode.ORDER_ERRPR);
				res.setMessage("只有支付成功待审核，处理中，打包中，已发货，或完成才能关闭订单");
			}
		} else {
			
			res.setErrorCode(ErrorCode.ORDER_ERRPR);
			res.setMessage("查无订单");
		}
		return res;
	}
	
	/**
	 * 关闭订单模拟   积分充值的处理过程
	 * @Title: dealClosePrompt 
	 * @Description: TODO
	 * @author xujinding
	 * @param @param orderNo
	 * @param @return
	 * @return Result
	 * @throws
	 */
	public Result<CloseOrderPrompt> dealClosePrompt(String orderNo) {
		Result<CloseOrderPrompt> res = new Result<>();
		CloseOrderPrompt closeOrderPrompt = new CloseOrderPrompt();
		OrderInfo orderInfo = orderInfoMap.findOrderInfoByOrderNo(orderNo);
		if (orderInfo != null) {
			if (OrderStatusEnum.支付成功待审核.getValue().equals(orderInfo.getOrderStatus()) || OrderStatusEnum.处理中.getValue().equals(orderInfo.getOrderStatus())
					|| OrderStatusEnum.已发货.getValue().equals(orderInfo.getOrderStatus()) || OrderStatusEnum.打包中.getValue().equals(orderInfo.getOrderStatus())
					|| OrderStatusEnum.订单完成.getValue().equals(orderInfo.getOrderStatus())) {
				PayOrder payOrder = payOrderMapper.selectByPrimaryKey(orderInfo.getPaymentOrderId());
				// 查出总积分 和充值， 先 返还 在 回收
				MemberAccount userAccount = new MemberAccount();
				userAccount.setMemberId(orderInfo.getCreateMemberId());
				userAccount.setSysId(orderInfo.getSysId());
				MemberAccount memberAccount = memberAccountService.findByMemberAccount(userAccount);
				
				if (memberAccount == null) {
					res.setErrorCode(ErrorCode.MEMBER_ACCOUNT_NOT_EXIST);
					res.setMessage("会员帐号不存在");
					return res;
				}
				
				// 用户当前
				Integer totalIntegral = memberAccount.getTotalIntegral() == null ? 0 : memberAccount.getTotalIntegral();
				BigDecimal totalAmount = memberAccount.getTotalAmount() == null ? new BigDecimal(0.00) : memberAccount.getTotalAmount();
				
				// 用户购物使用的
				Integer useJfSum = payOrder.getUseJfSum() == null ? 0 : payOrder.getUseJfSum();
				BigDecimal useStoreValue = payOrder.getUseStoreValue() == null ? new BigDecimal(0.00) : payOrder.getUseStoreValue();
				
				// 回收购物车规则 积分和 充值
				List<RuleSetUseLog> ruleLogs = ruleSetUseLogMapper.findIntegralAndBalance(orderInfo.getId());
				Integer ruleIntegralSum = 0;
				BigDecimal ruleuStoreSum = new BigDecimal(0.00);
				
				if (ruleLogs != null && !ruleLogs.isEmpty()) {
					for (RuleSetUseLog rsl : ruleLogs) {
						BigDecimal giveNum = rsl.getGiveNum() == null ? new BigDecimal(0.00) : rsl.getGiveNum();
						// List<String> ruleIds = StringUtil.splitString(rsl.getGiveRuleSetIds());
						if (ShowType.GIVE_TOPUP_BALANCE.toString().equals(rsl.getShowType())) {
							ruleuStoreSum = ArithUtil.add(ruleuStoreSum, giveNum);
						}
						if (ShowType.GIVE_INTEGRAL.toString().equals(rsl.getShowType())) {
							ruleIntegralSum = giveNum.intValue() + ruleIntegralSum;
						}
					}
				}
				// 确认收货正常送的积分 要回收
				int receipt = 0;
				if (OrderStatusEnum.订单完成.getValue().equals(orderInfo.getOrderStatus())) {
					receipt = orderInfo.getGiveJfSum() == null ? 0 : orderInfo.getGiveJfSum().intValue();
				}
				
				// 小于 0 就给提示
				Integer finshIntegral = totalIntegral + useJfSum - ruleIntegralSum - receipt;
				// if (finshIntegral < 0) {
				closeOrderPrompt.setIntegral(finshIntegral);
				// }
				BigDecimal finshStore = ArithUtil.sub(ArithUtil.add(totalAmount, useStoreValue), ruleuStoreSum);
				// if (finshStore.doubleValue() < 0) {
				closeOrderPrompt.setBalance(finshStore);
				res.setData(closeOrderPrompt);
				res.setErrorCode(ErrorCode.SUCCESS);
				// }
			} else {
				res.setErrorCode(ErrorCode.ORDER_ERRPR);
				res.setMessage("只有支付成功待审核，处理中，打包中，已发货，或完成才能关闭订单");
			}
		} else {
			res.setErrorCode(ErrorCode.ORDER_ERRPR);
			res.setMessage("查无订单");
		}
		return res;
	}
	
	/**
	 * 创建发给oms的订单信息
	* @Description:
	* @Title: 
	* @author: xujinding
	 * @throws CustomException 
	* @date: 2017年4月23日下午6:26:29
	 */
	public String createOrderToOms(OrderInfo orderInfo, Long sysUserId) throws CustomException {
		String sysName = "zuipin";
		OrderConsignee consignee = orderConsigneeMapper.selectByPrimaryKey(orderInfo.getConsigneeId());
		Member member = memberService.findById(orderInfo.getCreateMemberId());
		PayOrder payOrder = payOrderMapper.selectByPrimaryKey(orderInfo.getPaymentOrderId());
		if (payOrder == null) {
			throw new CustomException(ErrorCode.ORDER_ERRPR.getCode(), "付款单信息查询不到");
		}
		OrderInvoiceInfo invoice = orderInvoiceInfoMapper.selectByPrimaryKey(payOrder.getInvoiceInfoId());
		if (consignee == null || member == null || invoice == null) {
			throw new CustomException(ErrorCode.ORDER_ERRPR.getCode(), "收货信息,下单人信息,发票信息查询不到");
		}
		
		Map<String, Object> orderMap = new HashMap<String, Object>();
		Map<String, Object> consigneeMap = new HashMap<String, Object>();
		consigneeMap.put("address", consignee.getAddress());
		consigneeMap.put("cityCode", consignee.getCityCode());
		consigneeMap.put("conSigneeId", consignee.getId() + "");
		consigneeMap.put("countryCode", consignee.getCountyCode());
		consigneeMap.put("delFlag", "1");
		consigneeMap.put("memberId", orderInfo.getCreateMemberId() + "");
		consigneeMap.put("provinceCode", consignee.getProvinceCode());
		consigneeMap.put("phone", consignee.getPhone());
		if (StringUtil.isBlank(consignee.getPhone())) {
			consigneeMap.put("phone", consignee.getTelephone());
		}
		// consigneeMap.put("phone", consignee.getPhone());
		consigneeMap.put("receiptName", consignee.getReceiptName());
		consigneeMap.put("streetAdress", consignee.getStreetAddress());
		orderMap.put("cancleOrderTime", orderInfo.getCancelTime());
		orderMap.put("createOrderTime", orderInfo.getCreateTime());
		orderMap.put("delFlag", 1);
		orderMap.put("deliveryDate", "");
		
		// 如果是货到付款传 申通-货到付款
		if ((PayType.CASH_DELIVERY + "").equals(payOrder.getPayType())) {
			if (OrderInfo.SHIP_SF.equals(orderInfo.getExpressDeliveryCode())) {
				orderMap.put("deliveryMethod", OrderInfo.SF_HDFK);
			} else {
				orderMap.put("deliveryMethod", OrderInfo.ST_HDFK);
			}
		} else {
			orderMap.put("deliveryMethod", orderInfo.getExpressDeliveryName());
		}
		
		// 折钱价和折后价不要运费
		// BigDecimal discountAftPrice = ArithUtil.add(payOrder.getOrderSum(),
		// payOrder.getUseStoreValue());
		// BigDecimal discountBefPrice = ArithUtil.add(payOrder.getProductPaySum(),
		// payOrder.getFreightSum());
		
		BigDecimal discountBefPrice = payOrder.getProductPaySum();
		BigDecimal discountAftPrice = ArithUtil.sub(ArithUtil.add(payOrder.getOrderSum(), payOrder.getUseStoreValue()), payOrder.getFreightSum());
		orderMap.put("discountAftPrice", discountAftPrice);
		orderMap.put("discountPrice", ArithUtil.sub(discountBefPrice, discountAftPrice));
		orderMap.put("discountBefPrice", discountBefPrice);
		orderMap.put("feight", orderInfo.getFreightSum());
		orderMap.put("modCause", "");
		orderMap.put("orderId", orderInfo.getId() + "");
		orderMap.put("orderState", 2); // 订单状态 订单状态 1待审核 2处理中 3已发货 4已完成 5订单取消 6订单关闭 7申请退货中 8订单退货完成9配送中
		orderMap.put("outOrderNo", orderInfo.getOrderNo());
		orderMap.put("payFinshTime", payOrder.getConfimPayTime());
		
		if (PayOrder.YES.equals(payOrder.getPayStatus())) {
			orderMap.put("payStatus", 1);
		} else {
			orderMap.put("payStatus", 2);
		}
		if ((PayType.CASH_DELIVERY + "").equals(payOrder.getPayType())) {
			orderMap.put("paymentMethod", 2);
		} else {
			orderMap.put("paymentMethod", 1);
		}
		orderMap.put("promotionPrivilege", 0);
		orderMap.put("sendTime", "");
		if (PayOrder.YES.equals(payOrder.getPayStatus())) {
			orderMap.put("settleAfterPrice", ArithUtil.add(payOrder.getOrderSum(), payOrder.getUseStoreValue()));
			orderMap.put("settleleftPrice", ArithUtil.add(payOrder.getOrderSum(), payOrder.getUseStoreValue()));
		} else {
			orderMap.put("settleAfterPrice", 0);
			orderMap.put("settleleftPrice", 0);
		}
		
		orderMap.put("sysName", sysName);
		orderMap.put("updateFlag", "0");
		orderMap.put("totalOrders", ArithUtil.add(payOrder.getOrderSum(), payOrder.getUseStoreValue()));
		orderMap.put("totalWeight", payOrder.getTotalWeight());
		Map<String, Object> memberMap = new HashMap();
		memberMap.put("address", consignee.getAddress());
		memberMap.put("area", member.getAreaCode());
		memberMap.put("buyerRemark", orderInfo.getOrderRemark());
		memberMap.put("city", member.getCityCode());
		memberMap.put("customerRemark", orderInfo.getCustomerRemark());
		System.out.println("55");
		if (invoice != null) {
			memberMap.put("invoiceContent", invoice.getInvoiceContent());
			if ((InvoiceType.PERSONAL + "").equals(invoice.getInvoiceType())) {
				memberMap.put("invoiceTitle", InvoiceType.PERSONAL.getName());
			} else {
				memberMap.put("invoiceTitle", invoice.getInvoiceTitle());
			}
			memberMap.put("invoiceType", InvoiceType.getKeyByValue(invoice.getInvoiceType()));
		}
		
		memberMap.put("memberId", member.getId() + "");
		memberMap.put("memberName", member.getContactName());
		memberMap.put("phone", member.getPhone());
		memberMap.put("province", member.getProvinceCode());
		memberMap.put("sysName", sysName);
		memberMap.put("unitName", "");
		List<Object> orderItemList = new ArrayList<Object>();
		List<OrderDetail> orderDetails = orderDetailMapper.findOrderDetailListByOrderId(orderInfo.getId());
		for (OrderDetail od : orderDetails) {
			Map<String, Object> orderItemMap = new HashMap<String, Object>();
			orderItemMap.put("backCommodityNumber", 0);
			orderItemMap.put("cashbackDecuction", 0);
			orderItemMap.put("cashbackGiveMoney", 0);
			orderItemMap.put("cashbackMoney", 0);
			orderItemMap.put("commodityNumber", od.getProductNum());
			orderItemMap.put("delFlag", 1);
			
			if (od.getProductPrice() != null && od.getProductPrice().doubleValue() > 0) {
				orderItemMap.put("disCountRate", ArithUtil.mul(ArithUtil.div(od.getPurchasePrice(), od.getProductPrice()), new BigDecimal(100)));
			} else {
				orderItemMap.put("disCountRate", 0);
			}
			
			orderItemMap.put("giveJf", od.getGiveJfSum());
			orderItemMap.put("newWeight", 0);
			orderItemMap.put("orderInfoId", od.getOrderId() + "");
			orderItemMap.put("orderItemId", od.getId() + "");
			if (OrderDetail.IS_JF_PRODUCT_YES.equals(od.getIsJfProduct())) {
				orderItemMap.put("price", od.getJfPrice() / ConstantsUtil.ONE_TO_FIFTH);
			} else {
				orderItemMap.put("price", od.getProductPrice());
			}
			
			orderItemMap.put("priceSum", ArithUtil.mul(od.getProductPrice(), od.getProductNum()));
			orderItemMap.put("promotionPrivilege", 0 + "");
			orderItemMap.put("purchasePrice", od.getPurchasePrice());
			orderItemMap.put("purchasePriceSum", ArithUtil.mul(od.getPurchasePrice(), od.getProductNum()));
			orderItemMap.put("remark", "");
			orderItemMap.put("settlementPrice", od.getPurchasePrice());
			orderItemMap.put("specNumber", 1);
			orderItemMap.put("status", 0);
			orderItemMap.put("subtotal", ArithUtil.mul(od.getPurchasePrice(), od.getProductNum()));
			orderItemMap.put("useJf", od.getUseJfSum());
			orderItemMap.put("useJfMoney", od.getUseJfSum() / ConstantsUtil.ONE_TO_FIFTH);
			orderItemMap.put("usePacketAmt", od.getUseRedPacketSum());
			Map<String, Object> commodityInfoMap = new HashMap<String, Object>();
			ProductInfo product = productInfoService.selectByProSku(od.getProSku());
			if (product == null) {
				throw new CustomException(ErrorCode.ORDER_ERRPR.getCode(), "查无商品  商品编码为：：" + od.getProSku());
			}
			if (com.zuipin.enums.BusinessType.SELF_SALES.toString().equals(product.getBusinessType())) {
				commodityInfoMap.put("businessType", 1);
			} else {
				commodityInfoMap.put("businessType", 2);
			}
			commodityInfoMap.put("commodityId", product.getId());
			commodityInfoMap.put("commodityName", product.getProName());
			commodityInfoMap.put("commodityTypeId", 1);// 商品种类 1:正常商品 2:样品 3:预购 4:过时批次
			commodityInfoMap.put("netContent", product.getNetWeight());
			if (OrderDetail.IS_JF_PRODUCT_YES.equals(od.getIsJfProduct())) {
				commodityInfoMap.put("price", od.getJfPrice() / ConstantsUtil.ONE_TO_FIFTH);
			} else {
				commodityInfoMap.put("price", od.getProductPrice());
			}
			commodityInfoMap.put("remark", "");
			commodityInfoMap.put("showId", product.getProSku());
			commodityInfoMap.put("unit", product.getUnint());
			commodityInfoMap.put("weight", product.getWeight());
			orderItemMap.put("commodityInfo", commodityInfoMap);
			orderItemList.add(orderItemMap);
		}
		
		Map<String, Object> settleInfoMap = new HashMap<String, Object>();
		settleInfoMap.put("backMoneySum", 0);
		settleInfoMap.put("commoditiesSum", payOrder.getProductPaySum());
		settleInfoMap.put("freightSum", payOrder.getFreightSum());
		settleInfoMap.put("giveCashbackSum", payOrder.getGiveCashBackSum());
		settleInfoMap.put("giveJfSum", payOrder.getGiveJfSum());
		settleInfoMap.put("memberCommoditiesSum", payOrder.getProductPaySum());
		settleInfoMap.put("paymentSum", payOrder.getOrderSum());
		settleInfoMap.put("promotionPrivilege", 0);
		settleInfoMap.put("redPacketAmt", payOrder.getUseRedPacketSum());
		settleInfoMap.put("useJfMoneySum", payOrder.getUseJfSum() / ConstantsUtil.ONE_TO_FIFTH);
		settleInfoMap.put("useJfSum", payOrder.getUseJfSum());
		settleInfoMap.put("useStoreValueSum", payOrder.getUseStoreValue());
		orderMap.put("consignee", consigneeMap);
		orderMap.put("orderItemList", orderItemList);
		orderMap.put("orderMemberInfo", memberMap);
		orderMap.put("settleInfo", settleInfoMap);
		String json = JSONObject.toJSONString(orderMap, SerializerFeature.WriteMapNullValue).toString();
		log.info("发给OMS参数为 ：：" + json);
		String enStr = java.net.URLEncoder.encode(json);
		String omsResult = HttpUtil.post(sendOrderInfoToOms, "orderInfo", enStr);
		log.info("oms 返回参数为 ：：" + omsResult);
		JSONObject returnJson = JSONObject.parseObject(omsResult);
		if (returnJson != null && returnJson.get("success") != null && returnJson.getBoolean("success")) {
			if (returnJson != null && returnJson.get("splitOrderResult") != null && returnJson.getBoolean("splitOrderResult")) {
				updateOrderStatus(orderInfo.getOrderNo(), OrderStatusEnum.打包中.getIndex(), sysUserId, null, "后台客服审核通过", "", null);
			}
		} else {
			throw new CustomException(ErrorCode.ORDER_ERRPR.getCode(), "流向 oms 错误");
		}
		return omsResult;
	}
	
	/**
	 * 可以取消的订单--定时器
	 */
	@Override
	public List<Map<String, Object>> canCancelOrder() {
		return orderInfoMap.findCancelOrder();
	}
	
	@Override
	public Result findOrderLog(String orderNo) {
		
		return null;
	}
	
	public Object toNullByJSONull(Object obj) {
		
		if (obj instanceof JSONNull) {
			return null;
		}
		return obj;
	}
	
	/**
	 * cps--根据订单Id查询订单
	 */
	@Override
	public Result getOrderByIds(String ids) {
		Result res = new Result();
		String[] array = CommonUtils.splitBySymbol(ids, ",");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("ids", array);
		List<Map<String, Object>> list = orderInfoMap.getOrderByIds(paramMap);
		for (Map<String, Object> map : list) {
			List<OrderDetail> pros = orderDetailMapper.findOrderDetailListByOrderId(Long.valueOf(String.valueOf(map.get("orderId"))));
			map.put("products", pros);
		}
		res.setErrorCode(ErrorCode.SUCCESS);
		res.setData(list);
		return res;
	}
	
	/**
	 * 醉品分销--根据传入的orderid查询订单状态
	 */
	@Override
	public Map<String, Object> getOrderStatus(String data) {
		JSONObject json = JSONObject.parseObject(data);
		String[] array = CommonUtils.splitBySymbol(json.getString("orderId"), ",");
		Map<String, Object> reMap = new HashMap<String, Object>();
		if (array != null && array.length > 0) {
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("nos", array);
			List<Map<String, Object>> list = orderInfoMap.getOrderByIds(paramMap);
			for (Map<String, Object> map : list) {
				reMap.put(String.valueOf(map.get("orderNo")), OrderStatusEnum.getNameByValue(String.valueOf(map.get("orderStatus"))));
			}
		}
		return reMap;
	}
	
	/**
	 * 醉品分销--根据unionid查找醉品对应会员总消费金额
	 * @throws CustomException 
	 */
	@Override
	public Map<String, Object> getMemberTotal(String data) throws CustomException {
		JSONObject json = JSONObject.parseObject(data);
		String unionid = json.getString("unionid");
		ThirdAccount thirdAccount = new ThirdAccount();
		thirdAccount.setSysId(OrderInfo.ZP_SYS_ID);
		thirdAccount.setUnionId(unionid);
		thirdAccount.setPlatformId(ThirdAccount.THIRD_PLAT_WECHAT);
		ThirdAccount account = thirdAccountService.findByThirdAccount(thirdAccount);
		Map<String, Object> totalMap = new HashMap<String, Object>();
		if (account != null) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("memberId", account.getMemberId());
			map.put("sysId", OrderInfo.ZP_SYS_ID);
			map.put("orderStatus", OrderStatusEnum.订单完成.getValue());
			totalMap = orderInfoMap.getMembertotal(map);
			return totalMap;
		} else {
			throw new CustomException(ErrorCode.ORDER_ERRPR.getCode(), "查无unionid");
		}
	}
	
	/**
	 * 醉品分销--查找某一时段(入参时间<=时间<当前查询时间) 的分销会员消费信息
	 * @throws ParseException 
	 */
	public Map<String, Object> getDisbOrderInfo(String data) throws ParseException {
		List<Map<String, Object>> orderList = new ArrayList<>();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		JSONObject json = JSONObject.parseObject(data);
		String startTime = json.getString("date");
		Integer limitNum = 100;// 不传默认最多100条
		if (json.get("limitNum") != null) {
			limitNum = json.getInteger("limitNum");
		}
		String endTime = DateUtils.getCurrentDateTime();
		paramMap.put("limitNum", limitNum);
		paramMap.put("startTime", startTime);
		paramMap.put("endTime", endTime);
		// <!-- disbFlag =1 代表醉品分销特殊处理 -->
		paramMap.put("disbFlag", "1");
		List<Map<String, Object>> orderInfoList = orderInfoMap.getOrderByIds(paramMap);
		List<Long> memberIds = new ArrayList<Long>();
		List<Long> orderIds = new ArrayList<Long>();
		List<String> proSkus = new ArrayList<String>();
		// 组装订单id，一次性查详情，，组装memberId一次性查unionid,取出最大的时间
		String maxTime = null;
		if (orderInfoList != null && orderInfoList.size() > 0) {
			for (Map<String, Object> map : orderInfoList) {
				Long createMemberId = Long.valueOf(String.valueOf(map.get("createMemberId")));
				memberIds.add(createMemberId);
				Long orderId = Long.valueOf(String.valueOf(map.get("orderId")));
				orderIds.add(orderId);
				if (maxTime == null) {
					maxTime = Convert.toString(map.get("updateTime"));
				} else {
					if ((DateUtils.parseFullTime(Convert.toString(map.get("updateTime"))).getTime()) - (DateUtils.parseFullTime(maxTime).getTime()) > 0) {
						maxTime = Convert.toString(map.get("updateTime"));
					}
				}
			}
			
			// 查询unionId ，拼装 map
			List<ThirdAccount> thirdAccounts = thirdAccountService.findList(memberIds, ThirdAccount.THIRD_PLAT_WECHAT, OrderInfo.ZP_SYS_ID);
			Map<Long, ThirdAccount> thirdAccountMap = new HashMap<Long, ThirdAccount>();
			for (ThirdAccount ta : thirdAccounts) {
				thirdAccountMap.put(ta.getMemberId(), ta);
			}
			List<OrderDetail> ods = orderDetailMapper.findDetailByIds(orderIds);
			// 组装sku，一次性查询商品
			for (OrderDetail od : ods) {
				proSkus.add(od.getProSku());
			}
			
			Map<String, Map<String, Object>> proTypeMap = productInfoService.queryProInfoType(proSkus);
			
			MultiValueMap<Long, Map<String, Object>> orderDetailMap = new LinkedMultiValueMap<>();
			MultiValueMap<Long, String> itemMap = new LinkedMultiValueMap<>();
			// 构造符合醉品分销格式的订单详情，并构造item: ”sku1,sku2..”//订单商品sku
			for (OrderDetail od : ods) {
				Map<String, Object> odMap = new HashMap<String, Object>();
				odMap.put("sku", od.getProSku());
				odMap.put("name", od.getProductName());
				odMap.put("price", od.getProductPrice());
				odMap.put("total", ArithUtil.mul(od.getProductPrice(), od.getProductNum()));
				odMap.put("discountTotal", ArithUtil.mul(od.getPurchasePrice(), od.getProductNum()));
				odMap.put("num", od.getProductNum());
				if (proTypeMap != null && proTypeMap.get(od.getProSku()) != null) {
					Map<String, Object> tempMap = proTypeMap.get(od.getProSku());
					odMap.put("productType", Convert.toString(tempMap.get("productType")));
					odMap.put("brand", Convert.toString(tempMap.get("brand")));
					odMap.put("type", Convert.toString(tempMap.get("type")));
				} else {
					odMap.put("productType", "");
					odMap.put("brand", "");
					odMap.put("type", "");
				}
				// productType:"",//商品类别
				// brand:"",//商品品牌
				// type:""//类别为茶具填1，类别为茶叶且品牌为产地 直供填2，类别为茶叶且品牌不是产地直供填3
				orderDetailMap.add(od.getOrderId(), odMap);
				itemMap.add(od.getOrderId(), od.getProSku());
			}
			
			// 将订单详情放入订单列表中，并构造出符合醉品分销格式 （最终）
			for (Map<String, Object> map : orderInfoList) {
				Map<String, Object> orderMap = new HashMap<String, Object>();
				ThirdAccount ta = thirdAccountMap.get(Long.valueOf(String.valueOf(map.get("createMemberId"))));
				if (ta != null) {
					orderMap.put("unionid", ta.getUnionId());
				} else {
					orderMap.put("unionid", "");
				}
				orderMap.put("orderId", map.get("orderNo"));
				orderMap.put("orderAmount", map.get("grandTotal"));
				orderMap.put("date", map.get("updateTime"));
				
				// state:””, //操作0：订单已支付 1：退货 2: 取消订单(相对cbs的关闭)
				// 订单关闭的放 2 其他放 0
				if (OrderStatusEnum.已关闭.getValue().equals(String.valueOf(map.get("orderStatus")))) {
					orderMap.put("state", "0");
				} else {
					orderMap.put("state", "2");
				}
				// payment:,//0-货到付款 1-在线支付
				if ((PayType.CASH_DELIVERY + "").equals(String.valueOf(map.get("payType")))) {
					orderMap.put("payment", 0);
				} else {
					orderMap.put("payment", 1);
				}
				List<String> itemList = itemMap.get(Long.valueOf(String.valueOf(map.get("orderId"))));
				if (itemList != null && itemList.size() > 0) {
					orderMap.put("item", itemList.toString().substring(1, (itemList.toString().length() - 1)).replaceAll(" ", ""));
				} else {
					orderMap.put("item", "");
				}
				List<Map<String, Object>> pros = orderDetailMap.get(Long.valueOf(String.valueOf(map.get("orderId"))));
				// 订单详情，state为0时才需要
				orderMap.put("detail", pros);
				orderList.add(orderMap);
			}
		} else {
			maxTime = endTime;
		}
		
		Map<String, Object> returnMap = new HashMap<String, Object>();
		returnMap.put("orderList", orderList);
		returnMap.put("queryDate", maxTime);
		return returnMap;
	}
	
	/**
	 * @throws ParseException 
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 * 提交后台订单
	 *
	 * @Title: submitBackOrder 
	 * @author: wuyicheng
	 * @date: 2017年6月12日下午5:43:23 
	 * @param backPayOrderVO
	 * @return
	 * @throws CustomException
	 * @throws
	 */
	@Override
	public Result<BackOrderResultVo> submitBackOrder(BackOrderVo backOrderVo) throws CustomException, IllegalAccessException, InvocationTargetException, ParseException {
		Result<BackOrderResultVo> result = new Result<>(ErrorCode.SUCCESS);
		Map<String, Object> map = new HashMap<String, Object>();
		// 构建购物车
		List<ShoppingCart> shoppingCartList = shoppingCartService.createVirtualShoppingCart(backOrderVo.getOrderDetails(), backOrderVo.getCreateMemberId(), backOrderVo.getSysId());
		
		CartParam cartParam = new CartParam();
		cartParam.setBuyerId(backOrderVo.getCreateMemberId());
		cartParam.setSysId(backOrderVo.getSysId());
		cartParam.setCartIds(null);
		cartParam.setDevice(backOrderVo.getDevice());
		cartParam.setReceiveAddrId(backOrderVo.getReceiveAddrId());
		cartParam.setPayMethodCode(backOrderVo.getPayType());
		cartParam.setDeliveryMethodCode(backOrderVo.getExpressDeliveryCode());
		cartParam.setUseRedPacketId(backOrderVo.getUseRedPacketId());
		cartParam.setUseStoreBalance(0);
		cartParam.setUseBackBalance(0);
		cartParam.setOrderRemark(backOrderVo.getOrderRemark());
		cartParam.setCustomerRemark(backOrderVo.getCustomerRemark());
		cartParam.setCreateId(backOrderVo.getCreateId());
		cartParam.setIsUseIntegral(CartParam.IS_USE_INTEGRAL_NO_0);
		
		boolean isComplete = true;
		// 发票信息
		if (InvoiceType.ELECTRONIC_INVOICE.toString().equals(backOrderVo.getInvoiceType())) {
			// 电子发票
			if (StringUtil.isBlank(backOrderVo.getInvoiceTitle())
					|| (InvoiceType.COMPANY.toString().equals(backOrderVo.getInvoiceTitle())
							&& (StringUtil.isBlank(backOrderVo.getCompanyName()) || StringUtil.isBlank(backOrderVo.getTaxpayersNo())))
					|| StringUtil.isBlank(backOrderVo.getEmail())) {
				isComplete = false;
			}
			
		} else if (InvoiceType.ORDINARY_INVOICE.toString().equals(backOrderVo.getInvoiceType())) {
			// 普通发票
			if (StringUtil.isBlank(backOrderVo.getInvoiceTitle())
					|| (InvoiceType.COMPANY.toString().equals(backOrderVo.getInvoiceTitle()) && StringUtil.isBlank(backOrderVo.getTaxpayersNo()))) {
				isComplete = false;
			}
		} else if (InvoiceType.VTA_INVOICE.toString().equals(backOrderVo.getInvoiceType())) {
			// 增值税务发票
			if (StringUtil.isBlank(backOrderVo.getCompanyName()) || StringUtil.isBlank(backOrderVo.getTaxpayersNo()) || StringUtil.isBlank(backOrderVo.getRegisterAddress())
					|| StringUtil.isBlank(backOrderVo.getRegisterMobilePhone()) || StringUtil.isBlank(backOrderVo.getOpenBank())
					|| StringUtil.isBlank(backOrderVo.getOpenAccount())) {
				isComplete = false;
			}
		}
		if (!isComplete) {
			throw new CustomException(ErrorCode.ORDER_INVOICE_INCOMPLETE);
		}
		
		cartParam.setInvoiceCode(backOrderVo.getInvoiceType());
		cartParam.setInvoiceTitle(backOrderVo.getInvoiceTitle());
		cartParam.setInvoiceContent(backOrderVo.getInvoiceContent());
		cartParam.setCompanyName(backOrderVo.getCompanyName());
		cartParam.setTaxpayersNo(backOrderVo.getTaxpayersNo());
		cartParam.setRegisterAddress(backOrderVo.getRegisterAddress());
		cartParam.setRegisterMobilePhone(backOrderVo.getRegisterMobilePhone());
		cartParam.setOpenBank(backOrderVo.getOpenBank());
		cartParam.setOpenAccount(backOrderVo.getOpenAccount());
		cartParam.setEmail(backOrderVo.getEmail());
		// 运费由前端处理
		cartParam.setBackFreight(backOrderVo.getFreightSum());
		cartParam.setIsFromBack(CartParam.IS_FROM_BACK_YES_1);
		map = shoppingCartService.submitOrder(cartParam, shoppingCartList);
		BackOrderResultVo backOrderResultVo = new BackOrderResultVo();
		BeanUtils.populate(backOrderResultVo, map);
		result.setData(backOrderResultVo);
		return result;
	}
	
	@Override
	public Result getOrderByNos(String orderNos) {
		Result res = new Result();
		String[] array = CommonUtils.splitBySymbol(orderNos, ",");
		List<Map<String, Object>> list = null;
		if (array != null && array.length > 0) {
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("nos", array);
			list = orderInfoMap.getOrderByIds(paramMap);
			List<Long> orderIds = new ArrayList<Long>();
			List<String> proSkus = new ArrayList<String>();
			if (list != null && list.size() > 0) {
				// 得到组装orderId
				for (Map<String, Object> map : list) {
					Long orderId = Long.valueOf(String.valueOf(map.get("orderId")));
					orderIds.add(orderId);
				}
				
				List<OrderDetail> ods = orderDetailMapper.findDetailByIds(orderIds);
				// 组装sku，一次性查询商品
				for (OrderDetail od : ods) {
					proSkus.add(od.getProSku());
				}
				Map<String, Map<String, Object>> proTypeMap = productInfoService.queryProInfoType(proSkus);
				
				// 放入商品品牌等
				MultiValueMap<Long, OrderDetail> orderDetailMap = new LinkedMultiValueMap<>();
				for (OrderDetail od : ods) {
					if (proTypeMap != null && proTypeMap.get(od.getProSku()) != null) {
						Map<String, Object> tempMap = proTypeMap.get(od.getProSku());
						od.setProductType(Convert.toString(tempMap.get("productType")));
						od.setBrand(Convert.toString(tempMap.get("brand")));
						od.setType(Convert.toString(tempMap.get("type")));
					} else {
						od.setProductType("");
						od.setBrand("");
						od.setType("");
					}
					orderDetailMap.add(od.getOrderId(), od);
				}
				
				// 将商品详情放入订单
				for (Map<String, Object> map : list) {
					Long orderId = Long.valueOf(String.valueOf(map.get("orderId")));
					List<OrderDetail> pros = orderDetailMap.get(orderId);
					map.put("detail", pros);
				}
			}
		}
		res.setErrorCode(ErrorCode.SUCCESS);
		res.setData(list);
		return res;
	}
	
	/**
	 * @throws CustomException  
	 *
	 * @Title: toSettleByBack 
	 * @author: wuyicheng
	 * @date: 2017年6月15日下午6:17:40 
	 * @param calculateInfoVo
	 * @return
	 * @throws 
	 */
	@Override
	public Result<CalculateResultVo> toSettleByBack(CalculateInfoVo calculateInfoVo) throws CustomException {
		Result<CalculateResultVo> result = new Result<>(ErrorCode.SUCCESS);
		Map<String, Object> map = new HashMap<String, Object>();
		// 构建购物车
		List<ShoppingCart> shoppingCartList = shoppingCartService.createVirtualShoppingCart(calculateInfoVo.getDetailVos(), calculateInfoVo.getMemberId(),
				calculateInfoVo.getSysId());
		
		CartParam cartParam = new CartParam();
		cartParam.setBuyerId(calculateInfoVo.getMemberId());
		cartParam.setSysId(calculateInfoVo.getSysId());
		cartParam.setCartIds(null);
		cartParam.setDevice(calculateInfoVo.getDevice());
		cartParam.setReceiveAddrId(calculateInfoVo.getReceiveAddrId());
		cartParam.setPayMethodCode(calculateInfoVo.getPayType());
		cartParam.setDeliveryMethodCode(calculateInfoVo.getExpressDeliveryCode());
		cartParam.setUseRedPacketId(calculateInfoVo.getUseRedPacketId());
		cartParam.setUseStoreBalance(0);
		cartParam.setUseBackBalance(0);
		cartParam.setIsUseIntegral(CartParam.IS_USE_INTEGRAL_NO_0);
		
		map = shoppingCartService.calculateShoppingCart(cartParam, map, shoppingCartList);
		CalculateResultVo calculateResultVo = new CalculateResultVo();
		calculateResultVo.setMemberId(cartParam.getBuyerId());
		calculateResultVo.setFreightSum(new BigDecimal(Convert.toDouble(map.get("freight"))));
		calculateResultVo.setUseRedPacketSum(new BigDecimal(Convert.toDouble(map.get("redPacketDeduction"))));
		calculateResultVo.setProductPaySum(new BigDecimal(Convert.toDouble(map.get("proTotalAmount"))));
		calculateResultVo.setOrderSum(new BigDecimal(Convert.toDouble(map.get("actualPayTotalAmount"))));
		calculateResultVo.setRedPacketName(Convert.toString(map.get("redPacketName")));
		calculateResultVo.setAmountToIntegral(new BigDecimal(Convert.toDouble(map.get("amountToIntegral"))));
		calculateResultVo.setUseTotalIntegral(Convert.toInteger(map.get("useTotalIntegral")));
		calculateResultVo.setTotalIntegral(Convert.toInteger(map.get("totalIntegral")));
		calculateResultVo.setIsExistIntegralPro(Convert.toShort(map.get("isExistIntegralPro")));
		this.createProductAmountVo(map, calculateResultVo);
		result.setData(calculateResultVo);
		return result;
	}
	
	/** 
	 * 构建商品信息
	 * 
	 * @Title: createProductAmountVo 
	 * @author: wuyicheng
	 * @date: 2017年6月15日下午7:08:19 
	 * @param map
	 * @param calculateResultVo
	 * @return: void
	 * @throws 
	 */
	private void createProductAmountVo(Map<String, Object> map, CalculateResultVo calculateResultVo) {
		List<ProductAmountVo> productAmountVos = new ArrayList<>();
		// 正常商品
		List<ShoppingCart> shoppingCartList = (List<ShoppingCart>) map.get("cartList");
		if (shoppingCartList != null && shoppingCartList.size() > 0) {
			for (ShoppingCart shoppingCart : shoppingCartList) {
				ProductAmountVo productAmountVo = new ProductAmountVo();
				productAmountVo.setProSku(shoppingCart.getProSku());
				productAmountVo.setProductName(shoppingCart.getProName());
				productAmountVo.setPurchasePrice(shoppingCart.getPriorityPrice());
				productAmountVo.setProductNum(shoppingCart.getBuyNum());
				productAmountVo.setGiveJfSum(shoppingCart.getGiveIintegral());
				productAmountVo.setSubtotal(shoppingCart.getSubtotal());
				productAmountVo.setBusinessType(shoppingCart.getBusinessType());
				productAmountVo.setIsGivePro(ProductAmountVo.IS_GIVE_PRO_NO_0);
				productAmountVo.setIntegralPrice(shoppingCart.getIntegralPrice());
				productAmountVo.setIntegralSubtotal(shoppingCart.getIntegralSubtotal());
				productAmountVo.setActualPayIntegral(shoppingCart.getActualPayIntegral());
				productAmountVo.setActualPayIntegralSum(shoppingCart.getActualPayIntegralSum());
				productAmountVo.setIsIntegralPro(shoppingCart.getIsIntegralPro());
				productAmountVos.add(productAmountVo);
			}
		}
		// 赠送商品
		List<Gift> giftList = (List<Gift>) map.get("giftList");
		if (giftList != null && giftList.size() > 0) {
			for (Gift gift : giftList) {
				ProductAmountVo productAmountVo = new ProductAmountVo();
				productAmountVo.setProSku(gift.getProSku());
				productAmountVo.setProductName(gift.getProName());
				productAmountVo.setPurchasePrice(gift.getProPrice());
				productAmountVo.setProductNum(gift.getGiftNum());
				productAmountVo.setGiveJfSum(0);
				productAmountVo.setSubtotal(gift.getSubtotal());
				productAmountVo.setBusinessType(gift.getBusinessType());
				productAmountVo.setIsGivePro(ProductAmountVo.IS_GIVE_PRO_YES_1);
				productAmountVo.setIntegralPrice(gift.getIntegralPrice());
				productAmountVo.setIntegralSubtotal(0);
				productAmountVo.setActualPayIntegral(BigDecimal.ZERO);
				productAmountVo.setActualPayIntegralSum(0);
				productAmountVo.setIsIntegralPro(gift.getIsIntegralPro());
				productAmountVos.add(productAmountVo);
			}
		}
		calculateResultVo.setRedPacketList((List<RedPacketVo>) map.get("redPacketList"));
		calculateResultVo.setProductAmountVos(productAmountVos);
		calculateResultVo.setUseRuleSetList((List<UseRuleSetVo>) map.get("useRuleSetList"));
	}
	
	/** 
	 *
	 * @Title: deliveryOrder 
	 * @author: wuyicheng
	 * @date: 2017年6月19日下午6:15:37 
	 * @return
	 * @throws 
	 */
	@Override
	public List<Map<String, Object>> findCanComfimReceiptOrder(Long sysId) {
		return orderInfoMap.findCanComfimReceiptOrder(sysId);
	}
	
	@Override
	public List<CommentProductVo> orderProduct(Long orderId, Long memberId, String device, Long sysId) {
		OrderDetail param = new OrderDetail();
		param.setOrderId(orderId);
		param.setPremiumEnum(PremiumEnum.NO_PREMIUM.toString());
		List<OrderDetail> odList = orderDetailMapper.orderProduct(param);
		List<ProductExtVo> productExtList = new ArrayList<ProductExtVo>();
		// 主要是查询商品名称
		for (OrderDetail od : odList) {
			ProductExtVo pvo = new ProductExtVo();
			pvo.setProSku(od.getProSku());
			productExtList.add(pvo);
		}
		ProExtSerachVo svo = new ProExtSerachVo();
		svo.setDevice(device);
		svo.setMemberId(memberId);
		svo.setSysId(sysId);
		svo.setProductExtList(productExtList);
		svo.setShowOffShelf(false);
		Map<String, ProExtInfoVo> proMap = productInfoService.queryProExtInfo(svo);
		List<CommentProductVo> returnList = new ArrayList<>();
		for (OrderDetail od : odList) {
			ProExtInfoVo pevo = proMap.get(od.getProSku());
			CommentProductVo cpv = new CommentProductVo();
			if (pevo != null) {
				od.setImageUrl(pevo.getProImg());
				cpv.setProId(pevo.getProId());
				cpv.setProductExtId(pevo.getProductExtId());
			}
			cpv.setId(od.getId());
			cpv.setImageUrl(od.getImageUrl());
			cpv.setOrderId(od.getOrderId());
			cpv.setProSku(od.getProSku());
			cpv.setProductName(od.getProductName());
			cpv.setBuyNum(od.getProductNum());
			returnList.add(cpv);
		}
		return returnList;
	}
	
	/**
	 * 修改评论状态
	 */
	@Override
	public void modityIsComment(Long orderId) throws CustomException {
		OrderInfo oi = orderInfoMap.selectByPrimaryKey(orderId);
		if (oi != null) {
			if (!PayOrder.YES.equals(oi.getIsComment())) {
				oi.setIsComment(PayOrder.YES);
				orderInfoMap.updateByPrimaryKeySelective(oi);
			}
		} else {
			throw new CustomException(ErrorCode.ORDER_ERRPR.getCode(), "查无订单");
		}
	}
	
	/**
	 * 判断是否评价  true  已评价  false 否
	 */
	@Override
	public boolean isComment(Long orderId) throws CustomException {
		OrderInfo oi = orderInfoMap.selectByPrimaryKey(orderId);
		if (oi != null) {
			if (PayOrder.YES.equals(oi.getIsComment())) {
				return true;
			} else {
				return false;
			}
		} else {
			throw new CustomException(ErrorCode.ORDER_ERRPR.getCode(), "查无订单");
		}
	}
	
	/** 
	 * 统计商品购买订单数量 
	 * 
	 * @Title: countBuyOrderByProSku 
	 * @author: wuyicheng
	 * @date: 2017年7月13日下午7:56:09 
	 * @param memberId 会员ID
	 * @param sysId 系统ID
	 * @param proSku 商品SKU
	 * @param startTime 特价规则开始时间
	 * @param endTime 特价规则截至之间
	 * @return
	 * @return: int
	 * @throws 
	 */
	@Override
	public int countBuyOrderByProSku(Long memberId, Long sysId, String proSku, String startTime, String endTime) {
		return orderInfoMap.countBuyOrderByProSku(memberId, sysId, proSku, startTime, endTime);
	}
	
	/** 
	 * @Title: findOrderProductById 
	 * @Description: 根据订单Id查询商品
	 * @author xujinding
	 * @param @param orderId
	 * @param @param memberId
	 * @param @param device
	 * @param @param sysId
	 * @param @return
	 * @throws 
	 */
	@Override
	public List<OrderDetail> findOrderProductById(Long orderId, Long memberId, String device, Long sysId) {
		OrderDetail param = new OrderDetail();
		param.setOrderId(orderId);
		List<OrderDetail> odList = orderDetailMapper.orderProduct(param);
		return odList;
	}
	
	/**
	 * 功能描述：通知库存系统商品修改
	 * 
	 * @author :xujinding
	 * @createdTime : 2016年12月19日下午6:34:27
	 * @return
	 */
	public String createSendProductInfo(ProductInfo product) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("ID", product.getId());
		map.put("SPECIFICATIONS", product.getSpecifications());
		map.put("proNo", product.getProSku());
		map.put("proName", product.getProName());
		map.put("proUnit", product.getUnint());
		map.put("proNoSku", product.getProNo());
		
		// 理论上不会为空 --
		List<CategoryInfo> catList = categoryInfoService.findCategoryNav(product.getCatId());
		CategoryInfo oneCat = null;
		CategoryInfo secCat = null;
		CategoryInfo threeCat = null;
		for (CategoryInfo ci : catList) {
			if (CategoryInfo.ONE_LEVEL == ci.getCatLevel()) {
				oneCat = ci;
			} else if (CategoryInfo.TWO_LEVEL == ci.getCatLevel()) {
				secCat = ci;
			} else if (CategoryInfo.THREE_LEVEL == ci.getCatLevel()) {
				threeCat = ci;
			}
		}
		map.put("catId", threeCat == null ? null : threeCat.getId());
		map.put("secId", secCat == null ? null : secCat.getId());
		map.put("threeCatName", threeCat == null ? "" : threeCat.getCatName());
		map.put("secCatName", secCat == null ? "" : secCat.getCatName());
		map.put("firId", oneCat == null ? null : oneCat.getId());
		map.put("firCatName", oneCat == null ? "" : oneCat.getCatName());
		
		List<Map<String, Object>> addOrUpdateList = new ArrayList<Map<String, Object>>();
		// 为了迎合消费端 才构造list
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		addOrUpdateList.add(map);
		jsonMap.put("addOrUpdateList", addOrUpdateList);
		String json = JSONObject.toJSONString(jsonMap, SerializerFeature.WriteMapNullValue);
		log.info("修改商品:" + json);
		
		rocketMQService.doSendSyncMsg(RocketMqInfo.SYSTEM_NAME + RocketMqInfo.PRODUCT_GROUP, RocketMqInfo.SYSTEM_NAME + RocketMqInfo.PRODUCT_NAME, RocketMqInfo.SYSTEM_NAME_CIS,
				RocketMQTagEnum.TO_UPDATE_PRODUCT + "", CommonUtils.getUUID(), json);
		
		return "";
	}
	
	/**
	 * 根据发票id查询订单
	 * @Title: findOrderInfoByInvoiceId 
	 * @Description: TODO
	 * @author xujinding
	 * @param @param invoiceId
	 * @param @return
	 * @return OrderInfo
	 * @throws
	 */
	public OrderInfo findOrderInfoByInvoiceId(Long invoiceId) {
		return orderInfoMap.findOrderInfoByInvoiceId(invoiceId);
	}
	
	/**
	 * 根据订单id查询订单
	 * @Title: findOrderInfoByInvoiceId 
	 * @Description: TODO
	 * @author xujinding
	 * @param @param invoiceId
	 * @param @return
	 * @return OrderInfo
	 * @throws
	 */
	public OrderInfo findOrderInfoById(Long orderId) {
		return orderInfoMap.selectByPrimaryKey(orderId);
	}
	
}
